【C++】文件遍历

在c++中我们查找文件,需要一个结构体和几个函数。这些函数和结构体在头文件中,结构体为struct _finddata_t,函数为_findfirst、_findnext和_fineclose。
一,这两个函数都在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.
2._findnext()函数:int findnext(long,struct _finddata_t*);
第一个参数为文件句柄,
第二个参数同样为_finddata_t结构体指针;
若查找成功,返回0,失败返回-1.
注意:_findnext()第一个参数”路径句柄",返回的类型为intptr_t(long long),如果定义为long,在win7中没有问题,但是在win10中就要改为Long long或者intptr_t
3._findclose()函数:int _findclose(long)
只有一个参数,文件句柄。若关闭成功返回0,失败返回-1.

	string path = "E:\\pic\\testmorepic\\";
	char *filename ="E:\\pic\\testmorepic\\*.jpg";
	struct _finddata_t fileinfo;
	int k1;
	intptr_t handle;
	k1=handle = _findfirst(filename, &fileinfo);
	if (handle == -1)
		cout << "fail..." << endl;
	else
		cout << fileinfo.name << endl;
	img_names.push_back(path + fileinfo.name);
	while(!_findnext(handle,&fileinfo))
	{
		cout << fileinfo.name << endl;
		img_names.push_back(path+fileinfo.name);
	}
	_findclose(handle);

猜你喜欢

转载自blog.csdn.net/weixin_42104289/article/details/85054091