3

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.

Daniel Oliveira
  • 1,280
  • 14
  • 36
  • If you just want to redirect stdout to a file, use a shell redirection. If you want to learn how to redirect a file using C, you should rephrase the question. – William Pursell Nov 27 '16 at 22:55

1 Answers1

5

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.

pat
  • 12,587
  • 1
  • 23
  • 52