Writing ALL program output to a txt file in C++

前端 未结 5 1433
生来不讨喜
生来不讨喜 2021-01-05 02:45

I need to write all my program output to a text file. I believe it\'s done this way,

sOutFile << stdout;

where sOutFile is the ofstr

5条回答
  •  梦毁少年i
    2021-01-05 02:56

    If your program already uses cout/printf and you want to send EVERYTHING you currently output to a file, you could simply redirect stdout to point to a file before your existing calls: http://support.microsoft.com/kb/58667

    Relevant Code:

    freopen( "file.txt", "w", stdout );
    cout << "hello file world\n"; // goes to file.txt
    freopen("CON", "w", stdout);
    printf("Hello again, console\n"); // redirected back to the console
    

    Alternatively if you just want Some things to be printed to a file, you just want a regular file output stream: http://www.cplusplus.com/doc/tutorial/files.html

    Relevant Code:

    ofstream myfile;
    myfile.open("file.txt");
    myfile << "Hello file world.\n";
    printf("Hello console.\n");
    myfile.close();
    

    EDIT to aggregate answers from John T and Brian Bondy:
    Finally, if you're running it from the commandline, you can just redirect the output as everyone else mentioned by using the redirect operator ">" or append ">>":

    myProg > stdout.txt 2> stderr.txt
    

提交回复
热议问题