Create filename with current time stamp (c++) without c++20

Code

log.cpp

#include <fstream>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>

int main() {
    auto t = std::time(nullptr);
    auto tm = *std::localtime(&t);
    std::stringstream transTime;
    transTime << std::put_time(&tm, "%Y%m%d-%H%M%S");
    std::string fileName = "example-" + transTime.str() ;
    fileName.append(".txt");
    std::cout << fileName << std::endl;
    std::ofstream file(fileName, std::ios::app);
    file << "Writing this to a file.\n";
    file.close()
}

Build and run

> clang log.cpp -o log.exe
Or
> "c:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" x64
> cl log.cpp /Fe /EHsc

Comments

Popular posts from this blog