2016-03-03 47 views
1

在C++中,我想在每次運行我的程序時創建一個動態文件夾。無法創建動態文件夾名稱

#include <direct.h> // mkdir 
#include <iostream> // std 
#include <iomanip> // put_time 

int main(){ 
    time_t rawtime; 
    struct tm * timeinfo; 
    char buffer[40]; 
    time(&rawtime); 
    timeinfo = localtime(&rawtime); 
    //strftime(buffer, sizeof(buffer), "%d-%m-%Y %I:%M:%S", timeinfo); 
    strftime(buffer, sizeof(buffer), "%d_%m_%Y_%I_%M_%S", timeinfo); 
    std::string path = "C:/example/"; 
    path.append(std::string(buffer)); 
    mkdir(path.c_str()); 
    //system("pause"); 
    return 0; 
} 

我想創建一個名爲像"Example/03_03_2016_20_22_26"文件夾,但上面的代碼不會創造我想要的文件夾。

如果我刪除了path.append(std::string(buffer));行,它會在我的C目錄下創建一個名爲example的文件夾。

但是我想要一個根據完整日期和時間命名的文件夾。

我在哪裏錯了,或者我錯過了什麼?

+0

您是否嘗試打印完整路徑名?有什麼明顯的嗎?如果你使用它來在Windows中自己創建目錄,該怎麼辦? – BoBTFish

+0

是的,我確實打印了全名,但我也在Windows Visual Studio中嘗試過這種方式。 –

+0

「mkdir()」的返回值是什麼?這可能會告訴你發生了什麼事。此外,根據[Microsoft的文檔](https://msdn.microsoft.com/en-us/library/ms235326(v = vs.140).aspx),'mkdir()'已棄用,並且表示您應該使用'_mkdir()'。 – Steve

回答

0

我想問題是在斜線'/'。
在Windows上,最好使用反斜槓。 嘗試

std::string path="C:\\example\\" 
+0

解決了我的問題,謝謝 –

+0

好!我不是爲什麼我收到-1。我知道答案並不高雅,但它是解決問題的辦法。 – Matteo

3

我用類似用途的代碼在我的項目(SAVE_DIR是一個宏定義):

#include <time.h> 
#include <iomanip> 
#include <sstream> 

std::ostringstream pathstr; // a convenient way to construct strings 
std::time_t now = std::time(nullptr); // get the current time 
// insert the required parts into the stream 
pathstr << SAVE_DIR 
     << std::put_time(std::localtime(&now), "%Y_%m_%d_%H_%M_%S") << ".png"; 
std::string path = pathstr.str(); // and the result as std::str 

輸出:

/家庭/用戶/ PROG/render/rt/saves/2016_03_03_23_10_50.png

這有作爲純C++的好處,儘管它看起來有點笨拙,取決於你的口味。

至於你的代碼可能會失敗,我會首先在調試器中觀察字符串值,然後保存返回值mkdir()並根據規範檢查它:POSIX mkdir()