程式語言 - GNU - C/C++ - Print Format String to File



參考資訊:
https://stackoverflow.com/questions/5141960/get-the-current-time-in-c

main.c

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>

static int mylog(const char *fmt, ...)
{
    FILE *file = fopen("/tmp/mylog.txt", "a+");

    if (!file) {
        return -1;
    }

    va_list va = {0};
    time_t rawtime = {0};
    struct tm *timeinfo = {0};

    time(&rawtime);
    timeinfo = localtime(&rawtime);

    fprintf(file, "[%d%d%d-%d%d%d]",
        timeinfo->tm_year + 1900,
        timeinfo->tm_mday,
        timeinfo->tm_mon + 1,
        timeinfo->tm_hour,
        timeinfo->tm_min,
        timeinfo->tm_sec);

    va_start(va, fmt);
    vfprintf(file, fmt, va);
    va_end(va);

    fclose(file);
    return 0;
}

int main(int argc, char **argv)
{
    mylog("[%s] %d\n", "DBG", 100);
    return 0;
}