本节关键字:Linux、C语言、文件读写、日志记录
相关C库函数:printf、fopen、fprintf、fclose、vsprintf、localtime、
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
void WriteLogfile(char *msg, const char *prefile, const char *path)
{
time_t now = time(0);
struct tm* curclock = localtime(&now);
char filename[128];
static int oldwday=-1;
if (curclock->tm_wday != oldwday && oldwday != -1)
{
sprintf(filename, "%s/%d_%s.log", path, curclock->tm_wday, prefile);
remove(filename);
oldwday=curclock->tm_wday;
}
else
{
sprintf(filename, "%s/%d_%s.log", path, curclock->tm_wday, prefile);
}
int msec;
struct timeval ttv;
gettimeofday(&ttv, NULL);
msec = (ushort)(ttv.tv_usec/1000);
FILE *fp = fopen(filename, "a+");
if (!fp) return;
fprintf(fp,"%.4d-%.2d-%.2d %.2d:%.2d:%.2d.%.3d ",
curclock->tm_year+1900, curclock->tm_mon+1, curclock->tm_mday,
curclock->tm_hour, curclock->tm_min, curclock->tm_sec, msec);
fprintf(fp,"%s", msg);
fclose(fp);
}
void RecordLogs(char *fmt, ...)
{
char msg[300];
va_list args;
va_start(args, fmt);
vsprintf(msg, fmt, args);
va_end(args);
WriteLogfile(msg, "debug", "/home/user/log");
}
int main(void)
{
RecordLogs("this is my first log\n");
for (int i=10; i<20; i++)
RecordLogs("%s %dth log\n", "this is my ", i);
return 0;
}