You need to check the return values of your function calls. For most functions, you should check for error conditions. Doing so might have revealed the problem that if you want open()
to create the requested file in the event that it does not initially exist, then you need to add the O_CREAT
flag.
But that's not your main problem here -- you are dealing with a buffering issue. The output from the first printf()
is buffered in memory, so even though file descriptor 1 refers to your file at the time that printf()
is called, the data you write do not immediately get flushed to the destination file. You then restore the original stdout
file handle, so when the data are actually flushed, they go to the (restored) original stdout. Solve this by fflush()
ing before switching stdout
back:
int pfd = open("file", O_WRONLY | O_CREAT, 0777);
int saved = dup(1);
close(1);
dup(pfd);
close(pfd);
printf("This goes into file\n");
fflush(stdout); // <-- THIS
// restore it back
dup2(saved, 1);
close(saved);
printf("this goes to stdout");
Note also that dup2()
is cleaner and safer for duping a file descriptor onto a specific file descriptor number. You do that when you restore, but you should also do it for the initial redirection.