以下是一个可能的实现:

#include <stdio.h>
#include <time.h>

void myprintf(const char *fmt, ...) {
    time_t now = time(NULL);
    struct tm *timeinfo = localtime(&now);
    char timebuf[20];
    strftime(timebuf, sizeof(timebuf), '%Y-%m-%d %H:%M:%S', timeinfo);

    FILE *fp = fopen('output.txt', 'a');
    if (fp != NULL) {
        fprintf(fp, '%s ', timebuf);

        va_list args;
        va_start(args, fmt);
        vfprintf(fp, fmt, args);
        va_end(args);

        fclose(fp);
    }
}

这个函数首先获取当前时间,然后使用strftime函数将其格式化为一个字符串。然后打开指定文件(在这里是output.txt)用于追加内容。如果打开成功,就先将时间字符串输出到文件中,然后使用vfprintf函数将格式化字符串和变长参数列表打印到文件中。最后关闭文件。

使用这个函数的方式和printf类似。例如:

myprintf('Hello, world! %d\n', 42);

这将在output.txt文件中添加一行,类似于:

2021-11-22 14:30:00 Hello, world! 42
C语言实现自定义printf函数,添加时间戳并写入指定文件

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

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