C++ 使用_findfirst和_findnext查找文件

一、这两个函数均在io.h里面。
 
二、首先了解一下一个文件结构体:
struct _finddata_t {
    unsigned    attrib;
    time_t      time_create;   
    time_t      time_access;   
    time_t      time_write;
    _fsize_t    size;
    char        name[260];
};
 
time_t,其实就是long
而_fsize_t,就是unsigned long
 
现在来解释一下结构体的数据成员吧。
 
attrib,就是所查找文件的属性:_A_ARCH(存档)、_A_HIDDEN(隐藏)、_A_NORMAL(正常)、_A_RDONLY(只读)、 _A_SUBDIR(文件夹)、_A_SYSTEM(系统)。
 
time_create、time_access和time_write分别是创建文件的时间、最后一次访问文件的时间和文件最后被修改的时间。
 
size:文件大小
 
name:文件名。
 
 
三、用 _findfirst 和 _findnext 查找文件
 
1、_findfirst函数:long _findfirst(const char *, struct _finddata_t *);
 
第一个参数为文件名,可以用"*.*"来查找所有文件,也可以用"*.cpp"来查找.cpp文件。第二个参数是_finddata_t结构体指针。若查找成功,返回文件句柄,若失败,返回-1。
void dfsFolder(string folderPath, vector<string> &filenames)
{
	_finddata_t   FileInfo;
	string strfind = folderPath + "\\*";
	long  Handle = _findfirst(strfind.c_str(), &FileInfo);

	if (Handle == -1L)
	{
		cerr << "can not 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, filenames);
			}
		}
		else
		{
			string newPath = folderPath + "\\" + FileInfo.name;
			filenames.push_back(newPath);
			cout << folderPath.c_str() << "\\" << FileInfo.name << endl;
		}
	} while (_findnext(Handle, &FileInfo) == 0);

	_findclose(Handle);
}

这个时候测试的时候会在第29行while (_findnext(Handle, &FileInfo) == 0);处报错,错误信息为

经过查阅资料发现在x64环境下编译的话, _findfirst 还有 _findnext 则不能使用,会报错。

代码修改为:

void dfsFolder(string folderPath, vector<string> &filenames)
{
	__finddata64_t   FileInfo;
	string strfind = folderPath + "\\*";
	__int64   Handle = _findfirst64(strfind.c_str(), &FileInfo);

	if (Handle == -1L)
	{
		cerr << "can not 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, filenames);
			}
		}
		else
		{
			string newPath = folderPath + "\\" + FileInfo.name;
			filenames.push_back(newPath);
			cout << folderPath.c_str() << "\\" << FileInfo.name << endl;
		}
	} while (_findnext64(Handle, &FileInfo) == 0);

	_findclose(Handle);
}

即在3、5、29行分别使用匹配64位的函数即可。

最后成功在vector中存入了所有的文件名。



                
  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值