仅在错误期间创建日志文件

时间:2017-01-17 10:06:13

标签: c

我正在使用

登录错误消息
fpLogFile

并使用fopen打开fopen。 即使没有错误,0KB也会创建0KB文件。

如果创建了fopen文件,则会触发作业。因此,我只想在有错误的情况下创建日志。

如何使用{{1}}实现此目的还有其他方法吗?

2 个答案:

答案 0 :(得分:4)

fpLogFile设置为NULL,然后在每个fprintf之前,检查它是否仍为NULL。如果是,请打开文件。

答案 1 :(得分:1)

我可以为每个错误日志创建一个文件

#include <stdio.h>
#include <stdlib.h>

int g_Error_Num = 0;

#define LOG_INFO(...) \
do{\
    FILE *fpLogFile;\
    char file_name[32];\
    sprintf(file_name, "./Error_LOG_%d.txt", g_Error_Num++);\
    fpLogFile = fopen (file_name, "w+");\
    if (fpLogFile != NULL) {\
        fprintf(fpLogFile, __VA_ARGS__ ); \
        fclose(fpLogFile);\
    }\
} while( 0 )

int main(void)
{
    LOG_INFO("Test 1\n");
    LOG_INFO("Test 2\n");

    return 0;
}