2017-05-25 24 views
0

我試圖建立一個程序,它可以創建一個新的目錄每次被用來填充數據的時間。我希望文件夾的名稱是它創建時的時間戳。我已經寫了一個函數來創建時間戳並將其作爲字符串返回。C++如何使用保存在字符串中的文件路徑創建時間戳目錄?

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完整路徑和新的文件夾名稱的第二個字符串:\\ \\用戶\\丹尼爾\\的文件\\ VS17 25.5.2017- 16時47分51" 秒

我知道我可以使用

CreateDirectory(direc, NULL); 

做出一個目錄時,我有喜歡在我的字符串,但在LPCWSTR格式舉行的一個文件路徑。因此,其實我的問題是

  • 如何將我的字符串轉換成LPCWSTR格式CreateDirectory

  • 使用是否有我只是缺少

回答

0

由於您的文件夾一些其他的方式路徑字符串是char基於字符串,只需使用CreateDirectoryA()直接,而不是使用基於TCHARCreateDirectory()(這顯然是被映射到CreateDirectoryW()在您的項目)如:

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

啊謝謝!這工作。問題的另一部分是我的時間戳包含了未被接受的冒號。我只是將它們換成了句號,文件夾開始出現。好消息 –

相關問題