2011-04-11 109 views
15

我试图创建一个文件夹,如果它不存在。我使用的是Windows,而我对在其他平台上工作的代码不感兴趣。如何找出文件夹是否存在以及如何创建文件夹?

没关系,我找到了解决方案。我只是有一个包容性问题。答案是:

#include <io.h> // For access(). 
#include <sys/types.h> // For stat(). 
#include <sys/stat.h> // For stat(). 
#include <iostream> 
#include <string> 
using namespace std; 

string strPath; 
    cout << "Enter directory to check: "; 
    cin >> strPath; 

    if (access(strPath.c_str(), 0) == 0) 
    { 
     struct stat status; 
     stat(strPath.c_str(), &status); 

     if (status.st_mode & S_IFDIR) 
     { 
     cout << "The directory exists." << endl; 
     } 
     else 
     { 
     cout << "The path you entered is a file." << endl; 
     } 
    } 
    else 
    { 
     cout << "Path doesn't exist." << endl; 
    } 
+1

认真吗?您的第一个问题没有代码片段,并且此代码不反映该问题。这更像是“我的代码有什么问题(我没有发布)?” – 2011-04-11 13:33:12

+1

您应该发布编辑作为答案并接受它。 – 2011-04-11 13:38:48

+0

它没有让我发布它作为答案或评论。 – Sara 2011-04-13 09:42:28

回答

12

与POSIX兼容的调用是mkdir。当目录已经存在时,It默默失败。

如果您使用的是Windows API,那么CreateDirectory更合适。

13

使用boost::filesystem::exists检查文件是否存在。

11

boost::filesystem::create_directories只是这样做的:给它一个路径,它会在该路径中创建所有丢失的目录。

+0

在Google上搜索'boost检查目录是否存在,然后创建C++'将我带到这里作为第一个搜索结果。谢谢。 +1。 – rayryeng 2017-07-08 01:05:21

相关问题