How to write console output into a file?

Hi,

I want to write the console output into a file. Do someone know a way to do this?

when executing the program in cmd use > like: dir > asd.txt
Within the program, there are a couple of ways of doing this. The 'C' way of doing it is to use freopen to reopen stdout into a file. However, there is also the C++ way of doing it, which is to use std::ios::rdbuf to redirect the inner stream buffer to a file. Here is an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <fstream>

class RedirectStdOutput {
    public:
        RedirectStdOutput(std::ofstream& file)
            : _psbuf{file.rdbuf()}, _backup{std::cout.rdbuf()}
        {
            std::cout.rdbuf(_psbuf);
        }

        ~RedirectStdOutput() {
            std::cout.rdbuf(_backup);
        }

    private:
        std::streambuf* _psbuf;
        std::streambuf* _backup;
};

int main() {
    std::ofstream file ("file.txt");
    RedirectStdOutput rso (file);
    
    std::cout << "This is written to the file" << std::endl;

    return 0;
}


I haven't tested this (just knocked it up then), but you should get the idea.
Topic archived. No new replies allowed.