1. C/C++ 打印日志到文件示例代码
// LogPrint.cpp
#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#include <fcntl.h>
#include <time.h>
#define MAX_LEN 1024
#define LOG_FILE "./Test.log"
FILE *fd_log = nullptr;
int Log_Init()
{
int ret = -1;
if( (fd_log = fopen(LOG_FILE, "a+")) == nullptr)
{
printf("open file failed!\n");
}
else {
printf("open file successed!\n");
ret = 0;
}
return ret;
}
void Log_End()
{
fclose(fd_log);
}
// 使用方法同 printf
void Log_Printf(const char *fmt, ...)
{
static bool print_time = true; //是否要打印时间: 当 debug_mode 为真,且上一次是换行符结尾。
char message[MAX_LEN];
// 当前时间.
time_t timer = time(NULL);
strftime(message, 24, "\n[%Y-%m-%d %H:%M:%S] ", localtime(&timer));
va_list args;
va_start(args, fmt);
vsnprintf(message +