这是我写的函数,它迭代地创建一个文件夹树。这里的主要功能是:
#include <io.h>
#include <string>
#include <direct.h>
#include <list>
// Returns false on success, true on error
bool createFolder(std::string folderName) {
list<std::string> folderLevels;
char* c_str = (char*)folderName.c_str();
// Point to end of the string
char* strPtr = &c_str[strlen(c_str) - 1];
// Create a list of the folders which do not currently exist
do {
if (folderExists(c_str)) {
break;
}
// Break off the last folder name, store in folderLevels list
do {
strPtr--;
} while ((*strPtr != '\\') && (*strPtr != '/') && (strPtr >= c_str));
folderLevels.push_front(string(strPtr + 1));
strPtr[1] = 0;
} while (strPtr >= c_str);
if (_chdir(c_str)) {
return true;
}
// Create the folders iteratively
for (list<std::string>::iterator it = folderLevels.begin(); it != folderLevels.end(); it++) {
if (CreateDirectory(it->c_str(), NULL) == 0) {
return true;
}
_chdir(it->c_str());
}
return false;
}
的folderExists
例程如下:
// Return true if the folder exists, false otherwise
bool folderExists(const char* folderName) {
if (_access(folderName, 0) == -1) {
//File not found
return false;
}
DWORD attr = GetFileAttributes((LPCSTR)folderName);
if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
// File is not a directory
return false;
}
return true;
}
的示例性呼叫我测试上述功能与如下(和它的工作原理):
createFolder("C:\\a\\b\\c\\d\\e\\f\\g\\h\\i\\j\\k\\l\\m\\n\\o\\p\\q\\r\\s\\t\\u\\v\\w\\x\\y\\z");
这个函数没有经过非常彻底的测试,我不确定它还能与其他操作系统一起工作(但可能与少量修改兼容)。我目前使用Visual Studio 2010
与Windows 7.
为什么不使用Win32 API for那东西? – 2009-10-07 10:32:02
@JonathanFeinberg:在版本8之前的Windows中,路径名的解析受到严重限制(MAX_PATH长度限制,不支持“\\?\”前缀等)。您的评论确实适用于Windows 8及更高版本。 – IInspectable 2016-02-02 11:50:26