C++ How do I create a timestamped directory using a filepath held in a string?

1.3k Views Asked by At

I am trying to set up a program which can create a new directory every time it is used to fill with data. I want the name of the folder to be a timestamp of when it was created. I have already written a function which creates the timestamp and returns it as a string.

string timestamp() {

//create a timecode specific folder
// current date/time based on current system
time_t now = time(0);

struct tm timeinfo;
localtime_s(&timeinfo, &now);

// print various components of tm structure.
cout << "Year: " << 1900 + timeinfo.tm_year << endl;
int Y = 1900 + timeinfo.tm_year;
cout << "Month: " << 1 + timeinfo.tm_mon << endl;
int M = 1 + timeinfo.tm_mon;
cout << "Day: " << timeinfo.tm_mday << endl;
int D = timeinfo.tm_mday;
cout << "Time: " << 1 + timeinfo.tm_hour << ":";
int H = timeinfo.tm_hour;
cout << 1 + timeinfo.tm_min << ":";
int Mi = timeinfo.tm_min;
cout << 1 + timeinfo.tm_sec << endl;
int S = 1 + timeinfo.tm_sec;

string timestampStr;
stringstream convD, convM, convY, convH, convMi, convS;
convD << D;
convM << M;
convY << Y;
convH << H;
convMi << Mi;
convS << S;
cout << "Timestamp:" << endl;
timestampStr = convD.str() + '.' + convM.str() + '.' + convY.str() + '-' + convH.str() + ':' + convMi.str() + ':' + convS.str();
cout << timestampStr << endl;

return timestampStr;
}

This bit works fine and gives me a string with the current timestamp. I also have a second string with the path to the folders location which I combine to give the full path and new folder name in a string eg "C:\\Users\\Daniel\\Documents\\VS17\\25.5.2017-16:47:51"

I know I can use

CreateDirectory(direc, NULL);

to make a directory when I have a file path like the one held in my string but in LPCWSTR format. So really my question is

  • How do I convert my string into a LPCWSTR format to use in CreateDirectory

  • Is there some other way I am just missing

1

There are 1 best solutions below

1
On

Since your folder path string is a char based string, just use CreateDirectoryA() directly, instead of using the TCHAR based CreateDirectory() (which clearly is being mapped to CreateDirectoryW() in your project), eg:

string direc = "C:\\Users\\Daniel\\Documents\\VS17\\" + timestamp(); 
CreateDirectoryA(direc.c_str(), NULL);