Redirecting streams with freopen
What you'll learn: How to use the freopen function to swap standard input or output with a physical file.
In C, we are used to printf sending text to the screen and scanf reading text from the keyboard. These are tied to the "standard streams" called stdout and stdin. However, sometimes you want your program to act like a data processor that reads from a file and writes to a log without changing every single line of your code. This is where freopen comes in.
The Stream Switchboard
Think of freopen like a railway switch. Your program is a train running on the stdout track, heading toward the "Monitor" station. By calling freopen, you flip a lever that reroutes that same train onto a different track heading toward "File.txt." The train (your code) doesn't know the tracks have changed; it just keeps moving forward, but it ends up at a different destination.
This is incredibly useful for debugging or competitive programming. You can write your logic using familiar functions, then flip the switch at the start of main to handle file data.
Using freopen
The function takes three arguments: the filename, the mode (like "r" for read or "w" for write), and the stream you want to redirect.
#include <stdio.h>
int main() {
// Redirect standard output to a file named "log.txt"
// After this line, printf will no longer show up on the screen!
freopen("log.txt", "w", stdout);
printf("This message is sent to the file, not the screen.\n");
printf("We are using standard printf, but the destination changed.");
// Close the stream (this also closes the file)
fclose(stdout);
return 0;
}
Why use it?
The beauty of freopen is that it allows you to reuse existing code. If you have a complex function that performs twenty printf calls to format a report, you don't need to rewrite it to use fprintf and pass a file pointer around. You simply redirect stdout at the very beginning of your program, and every standard output function follows the new path automatically.
One thing to remember: once you redirect a stream like stdout to a file, it is difficult to "point" it back to the screen in a way that works across all operating systems. Use this technique when you want the redirection to last for the duration of the program's task.
Key takeaway
The freopen function redirects a standard stream (like stdin or stdout) to a file, allowing standard functions like scanf and printf to read from or write to files automatically.