打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
VC 遍历指定目录下的文件
//用于输出指定目录下的所有文件的文件名,包括子目录。

  版本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("%sn",szFile); //对文件进行操作
  }
}
while(FindNextFile(hFind,&wfd));
FindClose(hFind); //关闭查找句柄
}
  int main()
{
FindInAll("D:C++");
return 0;
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
用递归写Win32的文件夹遍历
文件遍历
两种方法使用VC遍历文件夹下所有文件和文件夹
使用FindFirstFile,FindNextFile遍历一个文件夹
在Windows下,如何遍历某目录里所有文件?
递归遍历某一路径下的所有文件(for windows or linux)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服