C++ 如何使用字符串中保存的文件路径创建带时间戳的目录

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

本文关键字:创建 时间戳 路径 文件 字符串 何使用 保存 C++      更新时间:2023-10-16

我正在尝试设置一个程序,该程序可以在每次用于填充数据时创建一个新目录。我希望文件夹的名称是创建时的时间戳。我已经编写了一个创建时间戳并将其作为字符串返回的函数。

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;
}

这个位工作正常,给了我一个带有当前时间戳的字符串。我还有第二个字符串,其中包含文件夹位置的路径,我将其组合在一起以在字符串中提供完整路径和新文件夹名称,例如"C:\\Users\\Daniel\\Documents\\VS17\\25.5.2017-16:47:51"

我知道我可以使用

CreateDirectory(direc, NULL);

当我有一个文件路径时,创建一个目录,就像我的字符串中保存的文件路径一样,但采用 LPCWSTR 格式。所以我的问题是

  • 如何将我的字符串转换为 LPCWSTR 格式以在创建目录中使用

  • 我只是想念其他方式吗

由于您的文件夹路径字符串是基于char的字符串,因此只需直接使用CreateDirectoryA(),而不是使用基于TCHARCreateDirectory()(显然正在映射到项目中的CreateDirectoryW()(,例如:

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