我写了一段简单的代码来对每个文件夹(包括子文件夹)中的所有文件执行某些操作。
当路径中包含空格字符时,程序会崩溃并调用INVALID_HANDLE_VALUE
。以下是该函数:
int dirListFiles(char* startDir)
{
HANDLE hFind;
WIN32_FIND_DATAA wfd;
char path[MAX_PATH];
sprintf(path, "%s\\*", startDir);
std::string fileName;
std::string s_path = startDir;
std::string fullPath;
fprintf(stdout, "In Directory \"%s\"\n\n", startDir);
if ((hFind = FindFirstFileA(path, &wfd)) == INVALID_HANDLE_VALUE)
{
printf("FindFirstFIle failed on path = \"%s\"\n", path);
abort();
}
BOOL cont = TRUE;
while (cont == TRUE)
{
if ((strncmp(".", wfd.cFileName, 1) != 0) && (strncmp("..", wfd.cFileName, 2) != 0))
{
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
sprintf(path, "%s\\%s", startDir, wfd.cFileName);
dirListFiles(path);
}
else
{
fileName = wfd.cFileName;
fullPath = s_path + "\\" + fileName;
std::string fileExt = PathFindExtension(fullPath.c_str());
if (fileExt == ".cpp")
{
... Some operation on file
}
}
}
cont = FindNextFile(hFind, &wfd);
}
FindClose(hFind);
例如,如果
FindNextFile
想要打开带有空格的文件名Program Files (x86)
,那么会导致错误并使程序退出。我该怎么做来支持空格?问题出在哪里?
0x8000
wchar(64kb)。之后,你就不需要再分配任何名称了。你只需要将文件名附加到缓冲区的当前位置即可。 - RbMmWCHAR buf[0x8000];
。 - RbMm