您的位置:首页 > 其它

VC 遍历指定目录下的文件

2008-08-02 22:14 351 查看
//转自:http://www.vcgood.com/forum_posts.asp?TID=2261&PN=1

//用于输出指定目录下的所有文件的文件名,包括子目录。

版本1:用string处理,方便,容易理解.

#include <windows.h>
#include <iostream>
#include <string>
using namespace std;

bool IsRoot(string Path)
{
string Root;
Root=Path.at(0)+"://";
if(Root==Path)
return true;
else
return false;
}

void FindInAll(string Path)
{
string szFind;
szFind=Path;
if(!IsRoot(szFind))
szFind+="//";
szFind+="*.*";
WIN32_FIND_DATA FindFileData;
HANDLE hFind=FindFirstFile(szFind.c_str(),& FindFileData);
if(hFind==INVALID_HANDLE_VALUE)
return ;
do
{
if(FindFileData.cFileName[0]=='.') //过滤本级目录和父目录
continue;
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) //如果找到的是目录,则进入此目录进行递归
{
string szFile;
if(IsRoot(Path))
szFile=Path+FindFileData.cFileName;
else
szFile=Path+"//"+FindFileData.cFileName;
FindInAll(szFile);
}
else //找到的是文件
{
string szFile;
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);
}

int main()
{
FindInAll("D://C++");
return 0;
}

版本2:编译器的通用性更强

#include <windows.h>
#include <iostream>
using namespace std;

BOOL IsRoot(LPCTSTR lpszPath)
{
TCHAR szRoot[4];
wsprintf(szRoot,"%c://",lpszPath[0]);
return (lstrcmp(szRoot,lpszPath)==0);
}

void FindInAll(::LPCTSTR lpszPath)
{
TCHAR szFind[MAX_PATH];
lstrcpy(szFind,lpszPath); //windows API 用lstrcpy,不是strcpy
if(!IsRoot(szFind))
lstrcat(szFind,"//");
lstrcat(szFind,"*.*"); //找所有文件
WIN32_FIND_DATA wfd;
HANDLE hFind=FindFirstFile(szFind,& wfd);
if(hFind==INVALID_HANDLE_VALUE) // 如果没有找到或查找失败
return;
do
{
if(wfd.cFileName[0]=='.')
continue; //过滤这两个目录
if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
TCHAR szFile[MAX_PATH];
if(IsRoot(lpszPath))
wsprintf(szFile,"%s%s",lpszPath,wfd.cFileName);
else
wsprintf(szFile,"%s//%s",lpszPath,wfd.cFileName);
FindInAll(szFile); //如果找到的是目录,则进入此目录进行递归
}
else
{
TCHAR szFile[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); //关闭查找句柄
}

int main()
{
FindInAll("D://C++");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: