Redirect stdout to a file

While dealing with redirecting output to a file you may use freopen().

Assuming you are trying to redirect your stdout to a file ‘output.txt‘ then you can write-

freopen("output.txt", "a+", stdout); 

Here “a+” for append mode. If the file exists then the file open in append mode. Otherwise a new file is created.

After reopening the stdout with freopen() all output statement (printf, putchar) are redirected to the ‘output.txt’. So after that any printf() statement will redirect it’s output to the ‘output.txt’ file.

If you want to resume printf()‘s default behavior again (that is printing in terminal/command prompt) then you have to reassign stdout again using the following code-

freopen("/dev/tty", "w", stdout); /*for gcc, ubuntu*/  

Or –

freopen("CON", "w", stdout); /*Mingw C++; Windows*/ 

However similar technique works for ‘stdin‘.

Leave a Comment