C++中如何查找一个文件夹,例如查找Temp这个文件夹?
要查找一个文件夹是否存在电脑上,该怎么实现?
[解决办法]
system("dir /b /a-d c:\\*.* >d:\\allfiles.txt");
//读文件d:\\allfiles.txt的内容即C:\\下所有文件的名字
system("dir /b /ad c:\\*.* >d:\\alldirs.txt");
//读文件d:\\alldirs.txt的内容即C:\\下所有子目录的名字
请记住,能用shell命令获取文件、文件夹信息或者操作文件、文件夹最好用shell命令获取或者操作,而不要用各种API获取或者操作,因为当遇到非法文件夹名或非法文件名或非法文件长度、非法文件日期、压缩文件、链接文件、稀疏文件……等各种意料之外的情况时,API会处理的不全面或陷入死循环,而shell命令不会。
[解决办法]
用MFC的CFileFind类比较容易实现。递归遍历C盘下所有的文件夹和子文件夹。
写一个函数实现你的功能。
CString FindTemp(CString strPath)
{
CFileFind finder;
BOOL bNext = finder.FindFile(strPath + "\\*.*");
while(bNext)
{
bNext = finder.FindNextFile();
if (finder.IsDirectory()&&!finder.IsDots())
{
if (finder.GetFileName() == "Temp")
return finder.GetFilePath();
else
{
CString strResult = FindTemp(finder.GetFilePath());
if (strResult =="没有找到!")
continue;
else
return strResult;
}
}
}
return "没有找到!";
}
然后调用这个函数
CString str = FindTemp("c:");
MessageBox(str);
没有这个文件夹得话就提示“没有找到!”
找到了的话就显示它的全路径