freopen() equivalent for c++ streams

freopen also works with cin and cout. No need to search for something new.

freopen("input.txt", "r", stdin); // redirects standard input
freopen("output.txt", "w", stdout); // redirects standard output

int x;
cin >> x; // reads from input.txt
cout << x << endl; // writes to output.txt

Edit: From C++ standard 27.3.1:

The object cin controls input from a stream buffer associated with the object stdin, declared in <cstdio>.

So according to the standard, if we redirect stdin it will also redirect cin. Vice versa for cout.

Leave a Comment