recovery中快速导出log到文件(freopen)

本文介绍了如何在recovery.cpp中使用recovery实现日志输出功能,通过重定向标准输出和错误输出到指定的日志文件,并在程序运行时将所有输出内容写入该文件。此外,提供了对`freopen`函数的帮助说明,解释了其用于改变标准输入输出流与文件关联的主要用途。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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).

       主要功能就是让标准输入输出流与文件相结合。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值