Problem after using freopen

Hey guys,

got a prob using the following code:

1
2
3
4
5
6
7
8
9
10
11
12
	cout << "Sorted by Input:" << endl << endl;
	SortData(spdata1, sptime, length);
	Swapdata(spdata1, sptime, length);
	Output1(chanoption);

	FILE *pOutput = freopen("output.txt", "w", stdout);
	Output1(chanoption);
	fclose(pOutput);
	freopen("CON", "w", stdout);

        cout << endl << endl << "Press any key to return to Mainmenu!" << endl;
	_getch();


Works fine until the end. Output is shown in console and then written to a file.
Afterwards the Output-Stream is set back to std and the last line appears in console again.

But when I go back to my Mainmenu system("cls"); doesn't work anymore.

Any ideas? :-(
Last edited on
No, it won't because you closed your end of the stdout handles.

You have several major design flaws that are impacting you, ranked in order of severity:

1. You are using freopen() to write to file instead of just writing to file.
  Fix your Output1 to write to an argument stream.

2. You are mixing C++ and C I/O. Don't do that.

3. You are requiring a human. You shouldn't do that, but fix the other problems first.

Hope this helps.
Thanks for your answer.

1. My program was written to just output to console. Now I wanted to chage that.
Thought freopen() would be the easiest way as I don't have to rewrite all my outputs to strings.
Isn't there any "quick" solution to write the console-output to a file?

2. That's how it was told by our teacher. Told us there is no prob in using cout / cin instead of printf / scanf. Is that wrong?
Last edited on
Told us there is no prob in using cout / cin instead of printf / scanf. Is that wrong?
I highlighted keyword here. Choose one: C standard streams or C++ ones.

My program was written to just output to console. Now I wanted to chage that.
How about good old-fashioned redirecting output into file when launching program through console?

program.exe > output.txt
Last edited on

program.exe > output.txt

This would redirect the whole output to file, wouldn't it?
But I would like to have the output in conole and file.
Use something like boost::tee_device. It is stream adaptor which allows tying two streams together. You can use resulting stream to write into two simultaneously.
http://stackoverflow.com/questions/999120/c-hello-world-boost-tee-example-program
Also JLBorges wrote teestream class: http://www.cplusplus.com/forum/general/64174/#msg347154
http://coliru.stacked-crooked.com/a/a05b6979ae626907

If you want to adapt existing program already using cout extensively and do not change any place where it can be found, you can replace cout buffer with homemade one.
A quick example using JLBorges code: http://coliru.stacked-crooked.com/a/ddfb2b7c9d0cde40
Topic archived. No new replies allowed.