Rok
Rok

Reputation: 3

File name as current time in seconds since the epoch in c++

I want to create a new file in c++ having file name as seconds (current time in seconds since the epoch) in FILE_FOLDER.

How can I modify the statement

myfile.open("/FILE_FOLDER/seconds");

Upvotes: 0

Views: 671

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

Getting the seconds since the epoch as a string is fairly easy:

#include <chrono>
#include <string>

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

Or simply:

#include <ctime>
#include <string>

auto now_sec_str = std::to_string(long(std::time(nullptr)));

Then just append that to your folder name:

myfile.open("/FILE_FOLDER/" + now_sec_str);

Upvotes: 1

Related Questions