how to create files named with current time?

前端 未结 4 471

I want to create a series of files under \"log\" directory which every file named based on execution time. And in each of these files, I want to store some log info for my p

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-15 03:05

    What about this:

    #include 
    #include 
    
    #define LOGNAME_FORMAT "log/%Y%m%d_%H%M%S"
    #define LOGNAME_SIZE 20
    
    FILE *logfile(void)
    {
        static char name[LOGNAME_SIZE];
        time_t now = time(0);
        strftime(name, sizeof(name), LOGNAME_FORMAT, localtime(&now));
        return fopen(name, "ab");
    }
    

    You'd use it like this:

    FILE *file = logfile();
    // do logging
    fclose(file);
    

    Keep in mind that localtime() is not thread-safe!

提交回复
热议问题