2012-07-05 90 views
0

創建一個目錄之前,我寫了這段代碼,以檢查是否在Windows和Unix存在的目錄,但我不知道它是否是正確的:檢查,如果是Windows或UNIX在C++

int writeFiles(std::string location) 
{ 

     // USED TO FILE SYSTEM OPERATION 
     struct stat st; 
     // DEFINE THE mode WHICH THE FILE WILL BE CREATED 
     const char * mode = "w+b"; 
     /* local curl variable */ 

     // CHECK IF THE DIRECTORY TO WHERE THE FILE ARE GOING EXIST 
     // IF NOT, CREATE IT 
     if(stat(location.c_str(), &st) != 0){ 
       #ifndef (defined _WIN32 || defined __WIN64) /* WIN32 SYSTEM */ 
       if (!CreateDirectory(location.c_str(), NULL)){ 
         std::string msg("The location directory did not exists, can't be created\n"); 
         throw std::runtime_error(msg); 
       } 
       #elif defined __unix__   /* in the case of unix system */ 
       if(mkdir(location.c_str(), S_IRWXU) != 0){ 
         std::string msg("The dest_loc directory did not exist, can't be created\n"); 
         throw std::runtime_error(msg); 
       } 
       #endif 

... more code down here. 

location是應該複製文件的路徑。但是,在開始複製文件之前,我必須檢查目錄是否存在,無論是Windows還是Linux。有人能給我一些關於這個問題的意見嗎? 謝謝

+0

你不確定哪一點? – hmjd 2012-07-05 15:09:43

+0

@hmjd #ifndef部分...我不確定它是否可以處理這兩種情況(Windows和Unix) – cybertextron 2012-07-05 15:11:52

+0

您是否嘗試過使用boost.filesystem? – PlasmaHH 2012-07-05 15:12:37

回答

2

你需要改變:

  #ifndef (defined _WIN32 || defined __WIN64) /* WIN32 SYSTEM */ 

到:

  #if (defined _WIN32 || defined __WIN64) /* WIN32 SYSTEM */ 

此測試是否無論_WIN32__WIN64定義,然後使用WINAPI代碼,如果是這樣的話。

你也許也改變:

  #elif defined __unix__   /* in the case of unix system */ 

只是:

  #else   /* in the case of non-Windows system */ 

由於大多數非Windows操作系統很可能有POSIX十歲上下的API mkdir等,你現在不要」沒有任何其他操作系統特定的代碼。

1

如果我必須編寫與文件系統交互的跨平臺代碼,我會使用跨平臺的文件系統API,如Boost FileSystem

4

的預處理指令(見Microsoft Predefined Macros列表)我會爲寫:

#ifdef _WIN32 

#else 

// Assume UNIX system, 
// depending on what you are compiling your code on, 
// by that I mean you only building on Windows or UNIX 
// (Linux, Solaris, etc) and not on Mac or other. 
#endif 

CreateDirectory()將失敗(返回FALSE)如果該目錄已存在,但將最後一個錯誤設置爲ERROR_ALREADY_EXISTS。改變你的CreateDirectory()使用正確處理這個問題:

if (!CreateDirectory(location.c_str(), NULL) && 
    ERROR_ALREADY_EXISTS != GetLastError()) 
{ 
    // Error message more useful if you include last error code. 
    std::ostringstream err; 
    err << "CreateDirectory() failure on " 
     << location 
     << ", last-error=" 
     << GetLastError(); 

    throw std::runtime_exception(err.str()); 
} 

說了這麼多,如果你有機會,以提高考慮使用boost::filesystem庫。

+0

我認爲__WIN32不是_WIN32? – djechlin 2012-07-05 15:19:40

+0

更何況64位? – djechlin 2012-07-05 15:19:57

+2

@djechlin,'_WIN32'在64位上定義。它是'_WIN32',而不是'__WIN32'。 – hmjd 2012-07-05 15:22:34

0

如果你可以認爲Windows有stat(),爲什麼你不能只使用mkdir()

但實際上,在Windows中可以無條件調用CreateDirectory(無前stat電話),並檢查是否GetLastError()回報ERROR_ALREADY_EXISTS

此外,std::string與ANSI功能CreateDirectoryA相匹配。宏使用CreateDirectory會導致Unicode不匹配。

相關問題