如何确定文件夹是否存在以及如何创建文件夹?
问题描述:
我想要创建一个文件夹(如果它不存在)。我使用Windows,我对在其他平台上工作的代码不感兴趣。
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.
没关系,我找到了解决方案。我只是有一个包含的问题。答案是:
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;
}
答
POSIX兼容通话 mkdir
。当该目录已存在时, It 会自动失败。
The POSIX-compatible call is mkdir
. It silently fails when the directory already exists.
如果您使用的是Windows API,请 CreateDirectory
更合适。
If you are using the Windows API, then CreateDirectory
is more appropriate.