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?
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?
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: