IO redirction

In some cases, programmer wants to redirect input or output as a file for debugging facility. This post will introduce how to redirect input and output in C and C++ program.

C Language

In C language, usually, scanf and printf are used for programming input and output in terminal respectively. To redirect them to a file, freopen() is a method.

freopen
1
2
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);

The code redirects standard input to data.in and output to data.out.

C++ Language

In C++, iostream is commonly used for input and output, like std::cin and std::cout. For redirction, rdbuf() can assign them to a file.

freopen
1
2
3
4
5
6
7
8
9
10
11
12
13
14
streambuf *cinbackup;
streambuf *coutbackup;
cinbackup = cin.rdbuf(); // back up cin's streambuf
coutbackup = cout.rdbuf(); // back up cout's streambuf
ifstream fin;
ofstream fout;
fin.open("data.in");
fout.open("data.out");
cin.rdbuf(fin.rdbuf()); // assign file's streambuf to cin
cout.rdbuf(fout.rdbuf()); // assign file's streambuf to cout
cin.rdbuf(cinbackup); // restore cin's original streambuf
cout.rdbuf(coutbackup);

The code above assign iostream to data.in and data.out.Then, it restores them to original streambuf.