C++实现文件的遍历

难过支持通配符。 如果要搜索指定格式的文件, 比如*.txt 表示任意名字以txt后缀  。*.*:表示 任意名字任意格式。

#include <iostream>

#include <io.h>
#include <string>
using namespace std;
bool transfer(char* fileName ) //遍历单层文件
{
int FileNum = 0;
_finddata_t fileInfo;// _finddata_t 是用来存储文件各种信息的结构体
long handle = _findfirst(fileName, &fileInfo);//搜索与指定的文件名称匹配的第一个实例,若成功则返回第一个实例的句柄,否则返回-1L;
if (handle == -1L)//返回-1L 未找到文件
{
cout << "failed to transfer files" << endl;
return false;
}
do
{
FileNum++;
cout << fileInfo.name << endl;
} while (_findnext(handle, &fileInfo) == 0);


cout << " files' number: " << FileNum << endl;
return true;
}


void dfsFolder(string folderPath ) //遍历目录下所有文件 
{
_finddata_t FileInfo;
string search = folderPath +"\\*";
long Handle = _findfirst(search.c_str(), &FileInfo);
if (Handle == -1L)
{
cout << "can't match the folder path" << endl;
exit(-1);
}
do{
//判断是否有子目录
if (FileInfo.attrib &_A_SUBDIR)
{
//系统在进入一个子目录时,匹配到的头两个文件(夹)是"."(当前目录),".."(上一层目录)。
if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
{
string newPath = folderPath + "\\" + FileInfo.name;
dfsFolder(newPath);
}
}
else
{
cout << folderPath << "\\" << FileInfo.name << endl;
}
} while (_findnext(Handle, &FileInfo) == 0);


_findclose(Handle);
}


int main()
{
long handle; //用于查找的句柄 
_finddata_t fileinfo; //文件信息的结构
char *to_search = "D:\\软件工程\\*.*"; //欲查找的文件,支持通配符(*.txt)  
handle = _findfirst(to_search, &fileinfo);  
if (handle == -1)
return -1;
cout <<  fileinfo.name << endl; //打印出找到的文件的文件名
while (!_findnext(handle, &fileinfo)) //循环查找其他符合文件,直到找不到其他的为止
//函数_findnext->搜索与_findfirst函数提供的文件名称匹配的下一个实例,若成功则返回0,否则返回-1
cout << fileinfo.name << endl;
_findclose(handle); //别忘了关闭句柄 
system("pause");
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值