C++不使用重新定向功能将所有printf输出存为日志文件
时间: 2024-02-24 07:58:00 浏览: 16
如果不想使用重定向功能,你可以将所有需要输出的信息先写入到一个字符串缓冲区中,然后再将这个缓冲区的内容写入到日志文件中。
具体步骤如下:
1. 定义一个字符串缓冲区,并使用 `sprintf` 函数将需要输出的信息写入到缓冲区中。例如:
```c++
#include <cstdio>
#include <cstring>
char buffer[1024];
int n = sprintf(buffer, "This is a log message.\n");
int x = 123;
n += sprintf(buffer+n, "The value of x is %d.\n", x);
```
2. 使用文件操作函数将缓冲区的内容写入到日志文件中。例如:
```c++
#include <cstdio>
#include <cstring>
char buffer[1024];
int n = sprintf(buffer, "This is a log message.\n");
int x = 123;
n += sprintf(buffer+n, "The value of x is %d.\n", x);
FILE* fp = fopen("log.txt", "w");
if (fp != nullptr) {
fwrite(buffer, sizeof(char), strlen(buffer), fp);
fclose(fp);
}
```
完整的代码示例:
```c++
#include <cstdio>
#include <cstring>
int main() {
char buffer[1024];
int n = sprintf(buffer, "This is a log message.\n");
int x = 123;
n += sprintf(buffer+n, "The value of x is %d.\n", x);
FILE* fp = fopen("log.txt", "w");
if (fp != nullptr) {
fwrite(buffer, sizeof(char), strlen(buffer), fp);
fclose(fp);
}
return 0;
}
```
运行后,可以在程序所在的目录下找到名为 `log.txt` 的文件,其中包含了所有的 `printf` 输出。