I'm in an operating systems course and doing assignments with C on Linux. In one of the assignments I was supposed to redirect and output to a file, but for some reason, I keep getting the output in the terminal instead. I tried writing a simple program to do just that and it still didn't work:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <dirent.h>
void main(int argc, char* argv[]) {
int file1 = open("./text_try", O_CREAT | O_EXCL, 0666) //open file
printf("write to screen\n"); //print to screen
int oldOut = dup(1); //save screen FD
dup2(file1,1); //change output stream from screen to file
printf("write to file"); //print to file
dup2(oldOut,1); //change output stream from file back screen
printf("write to screen"); //print to screen
}
other things I tried :
O_RDWR
)close
+ dup
combo instead on dup2
perror
to see if any step will tip me off as to why it doesn't work.STDOUT_FILENO
instead of 1 for outputwould really appreciate any help on this!
stdio normally buffers output to stdout
-- it's line-buffered when it's connected to a terminal, fully-buffered when connected to a file. Since you're not writing any newlines, it will not flush the buffer automatically in either mode. The buffer is flushed automatically when the program exits, at which time it gets written to the last stream that FD 1 is connected to.
Either turn off buffering with setvbuf()
, or flush the output explicitly between printf()
calls.
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <dirent.h>
void main(int argc, char* argv[]) {
int file1 = open("./text_try", O_CREAT | O_EXCL, 0666) //open file
printf("write to screen\n"); //print to screen
int oldOut = dup(1); //save screen FD
dup2(file1,1); //change output stream from screen to file
printf("write to file"); //print to file
fflush(stdout);
dup2(oldOut,1); //change output stream from file back screen
printf("write to screen"); //print to screen
fflush(stdout);
}