C/C++ overload terminal output to file txt

In C/C++ program testing, sometimes it is necessary to output and print a large amount of program information through the terminal, and saving the information as a log file is more convenient for program testing and debugging. The following two simple methods are recorded to redirect the printed information to the file

  1. Under the Linux system, you can directly use the terminal command to redirect the output of the program to a file (recommended)

./testOut2File > ./log.txt

In the above command, ./testOut2File is an executable file (it can be followed by program command line parameters), and ">" means redirect the output to the ./log.txt file

  1. Use the freopen() function and fclose() function in the "cstdio" header file

#include <iostream>
#include <cstdio>

int main() {
    // 重定向标准输出到 output.log
    freopen("./log.txt", "w", stdout);

    std::cout << "Hello, World!" << std::endl;
    std::cout << "This is a test." << std::endl;

    // 关闭文件
    fclose(stdout);
    return 0;
}

It should be noted that fclose(stdout) needs to be used at the end of the main function to restore the output stream, otherwise the program may crash.

Guess you like

Origin blog.csdn.net/weixin_44576482/article/details/128667501