c++重载终端输出到文件

c++重载终端输出到文件

在c++程序编写中,有时需要将终端的打印信息保存为日志文件,便于程序测试和debug,下面记录两种建议方法实现重定向打印信息

  1. 在linux系统下,可以直接使用终端命令重定向程序输出到文件中
1
./testOut2File > ./log.txt

上述命令中./testOut2File为可执行文件,">"表示重定向输出到./log.txt文件中

  1. 使用"cstdio"头文件中的freopen()函数与fclose()函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#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;
}

需要注意的是需要在main函数的最后使用fclose(stdout)将输出流恢复,否则可能导致程序崩溃。


c++重载终端输出到文件
https://izhuhaoran.github.io/2023/01/23/CPP_Note/c++重定向终端打印到文件/
作者
zhuhr
发布于
2023年1月23日
许可协议