C语言帝国主页 | 帝国论坛 | 加入收藏
       
C Language Empire
> > VC 遍历指定目录下的文件

BBS原贴地址:http://www.vcgood.com/bbs/forum_posts.asp?tid=2261
标题:VC 遍历指定目录下的文件
发布: coolker   点击: 7643   更新时间:2008-4-10

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

版本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;
}

返回页首