Redirect stdout to File, Exception Safety

I have written a method which redirects stdout to a file:

1
2
3
4
5
6
/* Redirects stdout to file. */
void OutputController::stdoutredi(const std::string &filePath) {
	if (!freopen(filePath.c_str(), "w", stdout)) {
		throw std::runtime_error("File could nod be opened!");
	}
}


However this crashes later if I enter an invalid path, even though I catch the exception. From my understanding this is because stdout gets closed when freopen is not succesful?

I have changed it to
1
2
3
4
5
6
void OutputController::stdoutredi(const std::string &filePath) {
	if (!freopen(filePath.c_str(), "w", stdout)) {
		freopen("CON", "w", stdout);
		throw std::runtime_error("File could nod be opened!");
	}
}


This seems to work well in manual tests. Is this code correct, or can it still crash if an invalid path is provided?
Another question: Even though this works in manual tests (I catch the exception of course) it still crashes in Google Test, does anyone know the reason for that?
> However this crashes later if I enter an invalid path, even though I catch the exception.
can't reproduce, provide a complete testcase.

> From my understanding this is because stdout gets closed when freopen is not succesful?
man wrote:
freopen()
The original stream (if it exists) is closed.
it will close on success too.
so `stdout' has no file associated, ¿why would that cause a crash?
True, it also closes when succesful, but when it's redirected to a File the app still works as expected.
Closing the stream doesn't crash the app right away, I think it crashes when I try to print the error message, which makes sense.
Google Test also prints some stuff when an exception occurs.

Anyway, I want to redirect the output back to the console if opening the file doesn't work, is my code doing that correctly or are there still cases where it could crash?
> I think it crashes when I try to print the error message
use a debugger and make sure where it crashes

> which makes sense.
no, it doesn't
It definitely does crash in printf. Although I don't understand the complete call stack. I assume it will crash in other printing functions too. Here is the call stack:

https://gyazo.com/55c93b9c356cb165c4d4cb42e22137a7

Why do you think it doesn't make sense? Printing to a closed stream sounds like something that would crash.
Topic archived. No new replies allowed.