Search code examples
c++datetimetimetext-filestime-t

How can I name the text file I create after the current date/time


First of all, my knowledge of X++ is minimal, I just need to edit the code I've been given. I have a C++ program which creates a text file and stores data in it. Right now the program is using:

outfile.open("C:/Users/Admin/Documents/MATLAB/datafile.txt", std::ios::app);

But I need to change this code so each time i run this code, it will create a new file name. My suggestion is to somehow incorporate the time/date as the file name, but I am unsure how to do this. I've tried researching around, and it looks like using time_t is the way to go, but I'm unsure how to utilize it for my case.

Is it possible to save the time/date as a variable, then use:

outfile.open("C:/Users/td954/Documents/MATLAB/<DEFINED VARIABLE>", std::ios::app);
//                                            ^^^^^^^^^^^^^^^^^^

if so, how would I go about this?

Thanks guys


Solution

  • Here's code:

    time_t currentTime = time(0);
    tm* currentDate = localtime(&currentTime);
    char filename[256] = {0};
    
    strcpy(filename, "C:/Users/Admin/Documents/MATLAB/datafile");
    strcat(filename, fmt("-%d-%d-%d@%d.%d.%d.txt",
           currentDate->tm_hour, currentDate->tm_min, currentDate->tm_sec,
           currentDate->tm_mday, currentDate->tm_mon+1,
           currentDate->tm_year+1900).c_str());
    
    outfile.open(filename, std::ios::app);
    

    tm* and time_t are in ctime header. fmt is just function like sprintf, which formats string. Implementation(not mine, found on stackoverflow IIRC):

    #include <cstdarg>
    std::string fmt(const std::string& fmt, ...) {
        int size = 200;
        std::string str;
        va_list ap;
        while (1) {
            str.resize(size);
            va_start(ap, fmt);
            int n = vsnprintf((char*)str.c_str(), size, fmt.c_str(), ap);
            va_end(ap);
            if (n > -1 && n < size) {
                str.resize(n);
                return str;
            }
            if (n > -1)
                size = n + 1;
            else
                size *= 2;
        }
        return str;
    }