recovery.cpp中log输出用recovery 实现.
大概样子如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static const char *TEMPORARY_LOG_FILE = "./temp.log";
int main(int argc, char **argv) {
time_t start = time(NULL);
// If these fail, there's not really anywhere to complain...
freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);
printf ("push me to log .\n");
printf("current time is %s \n", ctime(&start));
system("echo 'push log \n' >> ./temp.log");
}
gcc -g -o pushtolog main.c
./pushtolog
可以看到temp.log文件内容如下:
printf 输出的所有内容,都到处到temp.log文件了,简单有方便。
可以看下帮助: man freopen
The freopen() function opens the file whose name is the string pointed
to by path and associates the stream pointed to by stream with it. The
original stream (if it exists) is closed. The mode argument is used
just as in the fopen() function. The primary use of the freopen()
function is to change the file associated with a standard text stream
(stderr, stdin, or stdout).
主要功能就是让标准输入输出流与文件相结合。
本文介绍了如何在recovery.cpp中使用recovery实现日志输出功能,通过重定向标准输出和错误输出到指定的日志文件,并在程序运行时将所有输出内容写入该文件。此外,提供了对`freopen`函数的帮助说明,解释了其用于改变标准输入输出流与文件关联的主要用途。
578

被折叠的 条评论
为什么被折叠?



