Assigning the standard streams
This method of redirecting streams is known as direct assignment.
You can redirect a C standard stream by assigning a valid file pointer
to it, as follows:
FILE *stream;
stream = fopen("new.file", "w+");
stdout = stream;
You must ensure that the streams are appropriate; for example, do not assign a stream opened for w to stdin. Doing so would cause a function such as getchar() called for the stream to fail, because getchar() expects a stream to be opened for read access.
Similarly, you can redirect a standard stream under C++ by assignment:
ofstream myfile("myfile.data");
cout = myfile;
Again, you must ensure that the assigned stream is appropriate; for example, do not assign an fstream opened for ios::out only to cin. This will cause a subsequent read operation to fail.