Hi, I use Visual Studio 2015, and the code below doesn't work because the file "file.txt"
is created but it's always empty.
#include <conio.h>
#include <fstream>
#include <iostream>
int main() {
std::string outputFileName = "D:/file.txt";
bool printToFile = true;
std::streambuf *cout_oldBuf = nullptr;
if (printToFile) {
// Referenced from:
// https://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files
// https://www.quora.com/How-do-I-output-all-my-cout-s-to-a-text-file-in-C
std::ofstream out(outputFileName.c_str());
cout_oldBuf = std::cout.rdbuf(); // Save old buf
std::cout.rdbuf(out.rdbuf()); // Redirect std::cout to the file.
}
std::cout << "Hello World\n";
if (printToFile) {
std::cout.rdbuf(cout_oldBuf);
}
std::cout << "Write on screen\n";
_getch();
}
If it's impossible to solve the previous method then this is another method but it has an error, but note that this method can write to the file with success if the application/console is ran to the end, but not using break points:
#include <conio.h>
#include <fstream>
#include <iostream>
int main()
{
// Referenced from:
// https://stackoverflow.com/questions/10150468/how-to-redirect-cin-and-cout-to-files
// https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/freopen-s-wfreopen-s?view=msvc-170
FILE *stream;
errno_t err;
err = freopen_s(&stream, "D:/file.txt", "w", stdout);
if (err != 0) {
// TODO
}
std::cout << "Hello world!\n";
// Error on the line stdout = ...: expression must be a modifiable lvalue
fclose(stdout);
stdout = fdopen(1, "w"); //reopen: 1 is file descriptor of std output
_getch();
}