C++ 如何确定文件夹是否存在以及如何创建文件夹?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5621944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find out if a folder exists and how to create a folder?
提问by Sara
I'm trying to create a folder if it doesn't exist. I'm using Windows and I am not interested on my code working in other platforms.
如果文件夹不存在,我正在尝试创建一个文件夹。我使用的是 Windows,我对在其他平台上工作的代码不感兴趣。
Never mind, I found the solution. I was just having a inclusion problem. The answer is:
没关系,我找到了解决方案。我只是遇到了包容性问题。答案是:
#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;
}
采纳答案by Andy Finkenstadt
The POSIX-compatible call is mkdir
. Itsilently fails when the directory already exists.
POSIX 兼容调用是mkdir
. 当目录已经存在时,它会静默失败。
If you are using the Windows API, then CreateDirectory
is more appropriate.
如果您使用的是 Windows API,那么CreateDirectory
更合适。
回答by Alexey Malistov
Use boost::filesystem::exists
to check if file exists.
使用boost::filesystem::exists
检查文件是否存在。
回答by Mephane
boost::filesystem::create_directories
does just that: Give it a path, and it will create all missing directories in that path.
boost::filesystem::create_directories
就是这样做的:给它一个路径,它将在该路径中创建所有丢失的目录。