run_time_error run_time_error - 12 days ago 8
C++ Question

Using Output file as Input file in same program in cpp

I was wondering is it possible to write test case file and use that test cases as input file and produce another output file in the same program in c++.
So far, I have tried this:

freopen("input.txt","w",stdout);
for(int i=2;i<=20000;i++)cout<<i<< " ";
fclose(stdout);
cout<<"Finished writing test cases"<<endl;
freopen("input.txt","r", stdin);
freopen("output.txt","w",stdout);
....
//rest of the code including cout etc.//


I opened my input and output files. Input is okay, but output does not produce any output in output file/stdout.

Any help would be appreciated, thanks.

Answer

Remove this line :

fclose(stdout);

Put this line at the end of the program, or after the part when you are sure you won't write to a file instead of stdout.

I think the code will work as you expect it to be.