1
std::ofstream myFile ("report.csv");

So in my folder, I will get the file as "report.csv"

How can I add a timestamp to the file name making it look like (date)_(time)_report.csv?

I have included...

#include <windows.h>
#include <string>
#include <time.h>
using namespace std::chrono;

I do not wish to add more libraries.

Nard
  • 45
  • 1
  • 6

1 Answers1

3

Since you didn't specify if the timestamp should be UTC (recommended) or just local date-time, here are both ways:

#include <chrono>
#include <iomanip> // put_time
#include <fstream>
#include <sstream> // stringstream

int main()
{

    auto now = std::chrono::system_clock::now();
    auto UTC = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();

    auto in_time_t = std::chrono::system_clock::to_time_t(now);
    std::stringstream datetime;
    datetime << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X");
    
    // UTC
    std::ofstream myFile1("report_" + std::to_string(UTC) + ".csv");
    // DateTime
    std::ofstream myFile2("report_" + datetime.str() + ".csv");

    return 0;
}
Sandu Ursu
  • 1,181
  • 1
  • 18
  • 28