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;
}
相关文章推荐
- 【C语言提高22】const专题
- 【C语言提高21】关于字符串的一个例题
- 链表排序——插入排序(纯C语言版)
- C++UDP通信源码
- C/C++程序设计——指针与函数
- 普通二叉树C++实现
- C语言实现封装
- c_7: c语言函数
- 《C++标准程序库》笔记之二
- 派生类和基类的关系
- 一款C++静态分析工具 —— CppDepend
- C++ 下 typeof 的实现
- VS2012 打开C++项目时出现MSB8020的错误代码
- codeforces604B More Cowbell
- codeforces604C Alternative Thinking (脑洞大开 )
- c语言实现单链表
- C++11之美
- OJ提交题目中的语言选项里G++与C++的区别(转载)
- IOS C语言 指针
- 位图法查找算法