您的位置:首页 > 编程语言 > C语言/C++

C++实现文件的遍历

2015-12-03 23:17 573 查看

支持通配符。 如果要搜索指定格式的文件, 比如*.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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: