代码
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
FILE* fp = NULL;
char *get_cur_time()
{
static char s[32] = {0};
time_t t;
struct tm* ltime;
struct timeval stamp;
gettimeofday(&stamp, NULL);
ltime = localtime(&stamp.tv_sec);
s[0] = '[';
strftime(&s[1], 20, "%Y-%m-%d %H:%M:%S", ltime);
sprintf(&s[strlen(s)], ".%03ld]", (stamp.tv_usec/1000));
return s;
}
#define PRINT(tag, fmt, ...) printf("%s %s "fmt"\n", get_cur_time(), tag, ##__VA_ARGS__);fflush(fp)
int main(void)
{
int i = 0;
if(0 == (fp = freopen("./my.log", "a", stdout))) {
printf("Cannot open file.\n");
}
while (1) {
PRINT("log","hello world");
usleep(100000);
}
}
输出结果
编译执行以上代码,生成my.log文件,打开文件,如图: