I'm trying to write console data into a separate text file in cpp. Anybody help me with sample code.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- 在vscode如何用code runner打开独立的控制台窗口,以及设置好调试模式时窗口的编码?
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
There are various ways to do this. You could redirect it from the command line with
programname > out.txt
. Or you could usefreopen("out.txt","w",stdout);
at the start of your program.If you want to write from your own process, I'd suggest a simple print method
Then you can call
for console output, or
to write into a file "filename.out". Of course you gain most, if
print
is a class method that outputs all the object's specific information you need and this way you can direct the output easily to different streams.smerrimans answer should help you out.
There is also the option to implement your own streambuf and use it with std::cout and std::cerr to store printouts to file instead of printing to console. I did that a while ago to redirect printouts to some sort of rotating logs with timestamps.
You will need to read up a little bit on how it works and this book helped me get it right.
If that's not what you're after it is a bit of overkill though.
If you want to create a child process and redirect its output you could do something like this:
bbtrb wrote:
Better than this is of course
so that you can even have the manipulated output stream returned by the function.