如何查找文件夹是否存在并创建文件夹?

16

如果文件夹不存在,我想创建一个文件夹。我正在使用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
真的吗?你最初的问题没有代码片段,而这段代码也不反映出问题。这更像是一个“我的代码有什么问题[我没有发布]?”的问题。 - Andy Finkenstadt
1
你应该将编辑后的内容发布为答案并接受它。 - the_drow
它不让我将其发布为答案或评论。 - Sara
#include <sys/io.h>,而不是 #include <io.h>,对吗? - Groosha
3个回答

13

兼容POSIX的调用是mkdir在目录已经存在时会悄无声息地失败。

如果您使用的是Windows API,则更适合使用CreateDirectory


13

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


12

boost::filesystem::create_directories 的作用就是:给定一个路径,它将创建该路径中所有缺失的目录。


在谷歌上搜索“boost check directory exists then create C++”将我带到了这里,作为第一个搜索结果。谢谢。+1。 - rayryeng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接