- //转自:http://www.vcgood.com/forum_posts.asp?TID=2261&PN=1
- //用于输出指定目录下的所有文件的文件名,包括子目录。
- 版本1:用string处理,方便,容易理解.
- #include<windows.h>
- #include<iostream>
- #include<string>
- usingnamespacestd;
- boolIsRoot(stringPath)
- {
- stringRoot;
- Root=Path.at(0)+"://";
- if(Root==Path)
- returntrue;
- else
- returnfalse;
- }
- voidFindInAll(stringPath)
- {
- stringszFind;
- szFind=Path;
- if(!IsRoot(szFind))
- szFind+="//";
- szFind+="*.*";
- WIN32_FIND_DATAFindFileData;
- HANDLEhFind=FindFirstFile(szFind.c_str(),&FindFileData);
- if(hFind==INVALID_HANDLE_VALUE)
- return;
- do
- {
- if(FindFileData.cFileName[0]=='.')//过滤本级目录和父目录
- continue;
- if(FindFileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)//如果找到的是目录,则进入此目录进行递归
- {
- stringszFile;
- if(IsRoot(Path))
- szFile=Path+FindFileData.cFileName;
- else
- szFile=Path+"//"+FindFileData.cFileName;
- FindInAll(szFile);
- }
- else//找到的是文件
- {
- stringszFile;
- if(IsRoot(Path))
- szFile=Path+FindFileData.cFileName;
- else
- szFile=Path+"//"+FindFileData.cFileName;
- cout<<szFile<<endl;
- cout<<FindFileData.cFileName<<endl;
- }
- }
- while(FindNextFile(hFind,&FindFileData));
- FindClose(hFind);
- }
- intmain()
- {
- FindInAll("D://C++");
- return0;
- }
- 版本2:编译器的通用性更强
- #include<windows.h>
- #include<iostream>
- usingnamespacestd;
- BOOLIsRoot(LPCTSTRlpszPath)
- {
- TCHARszRoot[4];
- wsprintf(szRoot,"%c://",lpszPath[0]);
- return(lstrcmp(szRoot,lpszPath)==0);
- }
- voidFindInAll(::LPCTSTRlpszPath)
- {
- TCHARszFind[MAX_PATH];
- lstrcpy(szFind,lpszPath);//windowsAPI用lstrcpy,不是strcpy
- if(!IsRoot(szFind))
- lstrcat(szFind,"//");
- lstrcat(szFind,"*.*");//找所有文件
- WIN32_FIND_DATAwfd;
- HANDLEhFind=FindFirstFile(szFind,&wfd);
- if(hFind==INVALID_HANDLE_VALUE)//如果没有找到或查找失败
- return;
- do
- {
- if(wfd.cFileName[0]=='.')
- continue;//过滤这两个目录
- if(wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
- {
- TCHARszFile[MAX_PATH];
- if(IsRoot(lpszPath))
- wsprintf(szFile,"%s%s",lpszPath,wfd.cFileName);
- else
- wsprintf(szFile,"%s//%s",lpszPath,wfd.cFileName);
- FindInAll(szFile);//如果找到的是目录,则进入此目录进行递归
- }
- else
- {
- TCHARszFile[MAX_PATH];
- if(IsRoot(lpszPath))
- wsprintf(szFile,"%s%s",lpszPath,wfd.cFileName);
- else
- wsprintf(szFile,"%s//%s",lpszPath,wfd.cFileName);
- printf("%s/n",szFile);//对文件进行操作
- }
- }
- while(FindNextFile(hFind,&wfd));
- FindClose(hFind);//关闭查找句柄
- }
- intmain()
- {
- FindInAll("D://C++");
- return0;
- }
VC 遍历指定目录下的文件
最新推荐文章于 2023-04-14 22:09:03 发布