#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;
C代码重写printf将输出内容行首加上时间写入到指定文件中要求不使用vfprintf

原文地址: https://www.cveoy.top/t/topic/cpJq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录