C语言实现自定义printf函数,添加时间戳并输出到指定文件
#include <stdio.h> #include <time.h>
void myprintf(FILE *fp, const char *fmt, ...) { va_list args; va_start(args, fmt);
time_t rawtime;
struct tm *timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, '%Y-%m-%d %H:%M:%S ', timeinfo);
fprintf(fp, '%s', buffer);
vfprintf(fp, fmt, args);
va_end(args);
}
int main() { FILE *fp = fopen('output.txt', 'w'); if (fp == NULL) { printf('Failed to open file\n'); return 1; }
myprintf(fp, 'Hello, world!\n');
myprintf(fp, 'The answer is %d\n', 42);
fclose(fp);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/nvc5 著作权归作者所有。请勿转载和采集!