创build一个目录,如果它不存在

在我的应用程序,我想复制到另一个硬盘的文件,所以这是我的代码:

#include <windows.h> using namespace std; int main(int argc, char* argv[] ) { string Input = "C:\\Emploi NAm.docx"; string CopiedFile = "Emploi NAm.docx"; string OutputFolder = "D:\\test"; CopyFile(Input.c_str(), string(OutputFolder+CopiedFile).c_str(), TRUE); return 0; } 

所以在执行这个之后,它在D: HDD中显示了一个文件testEmploi NAm.docx但是我想要他创buildtesting文件夹,如果它不存在的话。

我想这样做,而不使用Boost库。

使用WINAPI CreateDirectory()函数来创建一个文件夹。

您可以使用此函数而不检查目录是否已经存在,因为它会失败,但GetLastError()将返回ERROR_ALREADY_EXISTS

 if (CreateDirectory(OutputFolder.c_str(), NULL) || ERROR_ALREADY_EXISTS == GetLastError()) { // CopyFile(...) } else { // Failed to create directory. } 

构建目标文件的代码不正确:

 string(OutputFolder+CopiedFile).c_str() 

这将产生"D:\testEmploi Nam.docx" :目录和文件名之间缺少路径分隔符。 修正示例:

 string(OutputFolder+"\\"+CopiedFile).c_str() 

可能最简单和最有效的方法是使用boost和boost :: filesystem函数。 这样你可以简单地建立一个目录,并确保它是平台独立的。

 const char* path = _filePath.c_str(); boost::filesystem::path dir(path); if(boost::filesystem::create_directory(dir)) { std::cerr<< "Directory Created: "<<_filePath<<std::endl; } 

这里是创建一个文件夹的简单方法…….

 #include <windows.h> #include <stdio.h> void CreateFolder(const char * path) { if(!CreateDirectory(path ,NULL)) { return; } } CreateFolder("C:\\folder_name\\") 

上面的代码适合我。

 #include <experimental/filesystem> // or #include <filesystem> namespace fs = std::experimental::filesystem; if (!fs::exists("src")) { // Check if src folder exists fs::create_directory("src"); // create src folder } 

_mkdir也会做这个工作。

 _mkdir("D:\\test"); 

https://msdn.microsoft.com/en-us/library/2fkk4dzw.aspx

你可以使用cstdlib

虽然 – http://www.cplusplus.com/articles/j3wTURfi/

 #include <cstdlib> const int dir= system("mkdir -p foo"); if (dir< 0) { return; } 

你也可以通过使用检查目录是否已经存在

 #include <dirent.h> 

使用CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs);

如果函数成功,则返回非零,否则返回NULL