2012-05-01 43 views
7

我需要使用mkdir C++函數在VS 2008中採用兩個參數並從VS 2005的mkdir C++函數

但是這個函數是在我們的代碼中使用過時,我需要寫一個獨立的產品(含只有mkdir函數)來調試一些東西。

我需要導入哪些頭文件?我使用了direct.h,但是編譯器抱怨這個參數不需要2個參數(原因是這個函數在VS 2005中被棄用)。

mkdir("C:\hello",0); 

回答

11

如果你想編寫跨平臺的代碼,你可以使用boost::filesystem程序

#include <boost/filesystem.hpp> 
boost::filesystem::create_directory("dirname"); 

這並添加庫的依賴,但機會是你要使用其他的文件系統程序以及和boost::filesystem有一些偉大的接口。

如果您只需要創建一個新目錄,並且只打算使用VS 2008,則可以像其他人注意到的那樣使用_mkdir()

+0

+1只要有可能就去跨平臺。 – pmr

+3

ISO C++不是跨平臺的?爲什麼在這裏添加boost依賴項?我不會-1或任何東西,但這是矯枉過正。爲什麼添加一個鏈接時間庫依賴關係只是爲了添加一個目錄?你知道,Boost文件系統只是* not *頭文件。 –

+0

我已經避免了與文件系統相關的功能,因爲它們主要是系統/編譯器特定的。我不確定'mkdir()',但是你可以指向一個引用,它被定義爲標準的ISO C++嗎? – Tibor

7

它的過時,但ISO C++符合的_mkdir()替代它,所以使用該版本。所有你需要調用它的目錄名稱,它的參數:

#include <direct.h> 

void foo() 
{ 
    _mkdir("C:\\hello"); // Notice the double backslash, since backslashes 
         // need to be escaped 
} 

這裏是MSDN原型:

INT _mkdir(爲const char *目錄名);

+3

該死,ninja'd。 – Electro

+1

@電子,鍵入更快,:) –

6

我的跨平臺解決方案(遞歸):

#include <sstream> 
#include <sys/stat.h> 

// for windows mkdir 
#ifdef _WIN32 
#include <direct.h> 
#endif 

namespace utils 
{ 
    /** 
    * Checks if a folder exists 
    * @param foldername path to the folder to check. 
    * @return true if the folder exists, false otherwise. 
    */ 
    bool folder_exists(std::string foldername) 
    { 
     struct stat st; 
     stat(foldername.c_str(), &st); 
     return st.st_mode & S_IFDIR; 
    } 

    /** 
    * Portable wrapper for mkdir. Internally used by mkdir() 
    * @param[in] path the full path of the directory to create. 
    * @return zero on success, otherwise -1. 
    */ 
    int _mkdir(const char *path) 
    { 
    #ifdef _WIN32 
     return ::_mkdir(path); 
    #else 
    #if _POSIX_C_SOURCE 
     return ::mkdir(path); 
    #else 
     return ::mkdir(path, 0755); // not sure if this works on mac 
    #endif 
    #endif 
    } 

    /** 
    * Recursive, portable wrapper for mkdir. 
    * @param[in] path the full path of the directory to create. 
    * @return zero on success, otherwise -1. 
    */ 
    int mkdir(const char *path) 
    { 
     std::string current_level = ""; 
     std::string level; 
     std::stringstream ss(path); 

     // split path using slash as a separator 
     while (std::getline(ss, level, '/')) 
     { 
      current_level += level; // append folder to the current level 

      // create current level 
      if (!folder_exists(current_level) && _mkdir(current_level.c_str()) != 0) 
       return -1; 

      current_level += "/"; // don't forget to append a slash 
     } 

     return 0; 
    } 
} 
+0

上面的代碼在folder_exists函數中存在一個錯誤。當你調用stat函數時,你應該檢查返回代碼是否有錯誤。如果它返回-1,則出現錯誤。在Visual Studio 2010(至少)上,如果該文件夾不存在並且所有標誌都將設置爲1,則該函數將返回-1。 我建議你這個編輯: INT RET = STAT(dirPath.c_str(),&st); \t \t \t 回報率(RET == 0)&&(st.st_mode&S_IFDIR)真:假; 這正常工作。 –