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

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

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

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

 

在C语言中,`freopen`函数可以用于将标准输入、输出或错误流重定向到指定的文件,同时可以指定文件的路径,从而实现将文件读取并保存到特定文件夹的功能[^4]。该函数的原型为: ```c FILE *freopen(const char *filename, const char *mode, FILE *stream); ``` 其中,`filename`是目标文件的路径,`mode`是文件操作模式(例如`"r"`表示只读,`"w"`表示写入),而`stream`则是要重定向的流(如`stdin`、`stdout`)。 若希望将标准输入流重定向到指定路径的文件,可使用如下代码: ```c #include <stdio.h> int main() { // 将标准输入流重定向到指定路径的文件 if (freopen("C:\\path\\to\\your\\input.txt", "r", stdin) == NULL) { perror("Error redirecting stdin"); return 1; } // 从文件读取数据 int a, b; scanf("%d %d", &a, &b); printf("Read values: %d and %d\n", a, b); // 输出将显示在控制台,除非stdout也被重定向 return 0; } ``` 在上述代码中,`freopen`将标准输入流(`stdin`)重定向到`input.txt`文件,程序随后通过`scanf`从该文件中读取数据。如果文件路径设置正确,程序会读取文件中的内容并进行处理[^2]。 类似地,如果需要将输出保存到特定目录下的文件,可以通过重定向`stdout`实现: ```c #include <stdio.h> int main() { // 将标准输出流重定向到指定路径的文件 if (freopen("C:\\path\\to\\your\\output.txt", "w", stdout) == NULL) { perror("Error redirecting stdout"); return 1; } // 输出内容将写入output.txt文件 printf("This text will be written to the file.\n"); return 0; } ``` 以上代码将标准输出流(`stdout`)重定向到`output.txt`文件,所有通过`printf`等输出函数输出的内容将被写入该文件中。通过这种方式,可以灵活地控制输入和输出的文件路径,从而满足将文件读取并保存到指定目录的需求[^3]。 需要注意的是,在使用`freopen`时,如果目标文件已经打开,则会先关闭该文件流。此外,文件路径应确保程序有访问权限,并且路径格式应符合操作系统的要求(例如Windows使用反斜杠`\`作为路径分隔符,但需在字符串中使用转义字符`\\`)。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值