Daniel Oliveira Daniel Oliveira - 5 days ago 5
C Question

fclose(stdout) vs close(STDOUT_FILENO) - C

I want to redirect STDOUT to a file on the disk. The point is to make the printf on my program write to a file instead of the console.

I saw some articles on the web where they used:

dup2(fileno(outputFile), STDOUT_FILENO);


Or:

close(STDOUT_FILENO);
dup(fileno(outputFile));


In every tutorial they use close() and it actually works. But I was curious and I tried to use fclose(stdout) instead but some error happened when I tried to use printf:

fclose(STDOUT_FILENO);
dup(fileno(outputFile));


Error:

Bad file descriptor


My question is, why does fclose() not work but close() does?

Thanks.

pat pat
Answer

STDOUT_FILENO is a numeric file descriptor (usually 1). When you use close, you release the descriptor, but then reassign it with dup2. Any output to that descriptor will now go to the new file.

stdout on the other hand is a FILE*, an object of sorts that contains a file descriptor. Doing printf formats output into a buffer associated with the FILE, and then writes the buffer to the descriptor (depending upon the buffering mode). When you fclose a FILE*, it (normally) closes the underlying descriptor, and frees the FILE object. The dup2 does not ressurect stdout, so printf fails.

Comments