查找文件的类 struct _finddata_t结构体用法,c++ 获取目录下面所有目录下面的文件路径

c++ 编程交流qq群 1026485358

 

到底如何查找文件呢?我们需要一个结构体和几个大家可能不太熟悉的函数。这些函数和结构体在的头文件中,结构体为struct _finddata_t,函数为_findfirst、_findnext和_fineclose。具体如何使用,我会慢慢讲来~

        首先讲这个结构体吧~ struct _finddata_t ,这个结构体是用来存储文件各种信息的。说实话,这个结构体的具体定义代码,我没有找到,不过还好,文档里面在_find里有比较详细的成员变量介绍。我基本上就把文档翻译过来讲吧:

unsigned atrrib: 文件属性的存储位置。它存储一个unsigned单元,用于表示文件的属性。文件属性是用位表示的,主要有以下一些:_A_ARCH(存档)、 _A_HIDDEN(隐藏)、_A_NORMAL(正常)、_A_RDONLY(只读)、_A_SUBDIR(文件夹)、_A_SYSTEM(系统)。这些都是在中定义的宏,可以直接使用,而本身的意义其实是一个无符号整型(只不过这个整型应该是2的几次幂,从而保证只有一位为 1,而其他位为0)。既然是位表示,那么当一个文件有多个属性时,它往往是通过位或的方式,来得到几个属性的综合。例如只读+隐藏+系统属性,应该为:_A_HIDDEN | _A_RDONLY | _A_SYSTEM 。

time_t time_create: 这里的time_t是一个变量类型(长整型?相当于long int?),用来存储时间的,我们暂时不用理它,只要知道,这个time_create变量是用来存储文件创建时间的就可以了。

time_t time_access: 文件最后一次被访问的时间。

time_t time_write: 文件最后一次被修改的时间。

_fsize_t size: 文件的大小。这里的_fsize_t应该可以相当于unsigned整型,表示文件的字节数。

char name [_MAX_FNAME ]:文件的文件名。这里的_MAX_FNAME是一个常量宏,它在头文件中被定义,表示的是文件名的最大长度。

        以此,我们可以推测出,struct _finddata_t,大概的定义如下:

        struct _finddata_t 
        { 
             unsigned attrib; 
             time_t time_create; 
             time_t time_access; 
             time_t time_write; 
             _fsize_t size; 
             char name[_MAX_FNAME]; 
        };

        前面也说了,这个结构体是用来存储文件信息的,那么如何把一个硬盘文件的文件信息“存到”这个结构体所表示的内存空间里去呢?这就要靠_findfirst、_findnext和_fineclose三个函数的搭配使用了。

        首先还是对这三个函数一一介绍一番吧……

long _findfirst( char *filespec, struct _finddata_t *fileinfo );

        返回值: 如果查找成功的话,将返回一个long型的唯一的查找用的句柄(就是一个唯一编号)。这个句柄将在_findnext函数中被使用。若失败,则返回-1。

参数:

        filespec:标明文件的字符串,可支持通配符。比如:*.c,则表示当前文件夹下的所有后缀为C的文件。

        fileinfo :这里就是用来存放文件信息的结构体的指针。这个结构体必须在调用此函数前声明,不过不用初始化,只要分配了内存空间就可以了。函数成功后,函数会把找到的文件的信息放入这个结构体中。

int _findnext( long handle, struct _finddata_t *fileinfo );

        返回值: 若成功返回0,否则返回-1。

参数:

handle:即由_findfirst函数返回回来的句柄。

        fileinfo:文件信息结构体的指针。找到文件后,函数将该文件信息放入此结构体中。

int _findclose( long handle );

返回值: 成功返回0,失败返回-1。

参数:

handle :_findfirst函数返回回来的句柄。

        大家看到这里,估计都能猜到个大概了吧?先用_findfirst查找第一个文件,若成功则用返回的句柄调用_findnext函数查找其他的文件,当查找完毕后用,用_findclose函数结束查找。恩,对,这就是正确思路。下面我们就按照这样的思路来编写一个查找D:/Music文件夹下的所有 mp3的音乐。

 

#include<iostream>
#include<io.h>
using namespace std;

const char *to_search="D:\\Music\\*.mp3";

void main()
{
	long handle;//用于查找句柄
	struct _finddata_t fileinfo;//文件信息的结构体
	handle=_findfirst(to_search,&fileinfo);//第一次查找
	if(-1==handle)
		return;
	printf("%s\n",fileinfo.name);//打印出第一个文件名
	while(!_findnext(handle,&fileinfo))
	{
		printf("%s\n",fileinfo.name);
	}
	_findclose(handle);//别忘了关闭句柄
}

 

 

 

 

 

 

哎呀,暴露了我喜欢的音乐了,还有好多呢,哈哈

 

 

下面是我自己添加的:

看到一段代码,也是提取文件夹里面的各个文件名的,这段代码可以提取子文件夹里面的文件名。比如我测试了一下,在F盘建立test文件夹,然后在该文件夹下建立了三个文件夹,1,2,3。 其中文件夹1里面是mp3文件,2里面是txt文件,3里面是docx文件

下面是代码:

 

#include<iostream>
#include<vector>
#include <string>
#include <io.h>
#include <list>  
using namespace std;


vector<string> getFiles(const string &folder,const bool all /* = true */) 
{
	vector<string> files;
	list<string> subfolders;
	subfolders.push_back(folder);

	while (!subfolders.empty()) {
		string current_folder(subfolders.back());

		if (*(current_folder.end() - 1) != '/') {    //确保地址是 “ ..../*” 结尾的
			current_folder.append("/*");
		}
		else {
			current_folder.append("*");
		}

		subfolders.pop_back();

		struct _finddata_t file_info;
		long file_handler = _findfirst(current_folder.c_str(), &file_info);

		while (file_handler != -1) 
		{
			if (all &&
				(!strcmp(file_info.name, ".") || !strcmp(file_info.name, ".."))) {
				if (_findnext(file_handler, &file_info) != 0) break;
				continue;
			}
#if 0
			斜杆/ 和 反斜杠\ 的区别基本上就是这些了,下面再讨论一下相对路径和绝对路径。
				./SRC/  这样写表示,当前目录中的SRC文件夹;
				../SRC/  这样写表示,当前目录的上一层目录中SRC文件夹;
				/SRC/   这样写表示,项目根目录(可以只磁盘根目录,也可以指项目根目录,具体根据实际情况而定)
#endif

			if (file_info.attrib & _A_SUBDIR) 
			{
				// it's a sub folder
				if (all)
				{
					// will search sub folder
					string folder(current_folder);
					folder.pop_back();         //  就是减去最后的*     string 的pop_back Delete last character   Erases the last character of the string, effectively reducing its length by one.
					folder.append(file_info.name);

					subfolders.push_back(folder.c_str());
				}
			}
			else
			{
				// it's a file
				string file_path;
				// current_folder.pop_back();
				file_path.assign(current_folder.c_str()).pop_back();
				file_path.append(file_info.name);
				  
				files.push_back(file_path);
			}

			if (_findnext(file_handler, &file_info) != 0) break;
		}  // while
		_findclose(file_handler);
	}

	return files;
}


void main()
{
	string path="F:/test";      //注意这里地址是  /                        \\   
	vector<string> out;

	out=getFiles(path,true);

	for(int i=0;i<out.size();i++)
	{
		cout<<out[i]<<endl;
	}
}

调试了半天,地址需要/ 

 



代码中判断 . 和 ..的还不太明白,感觉是不会有的啊。

 

 

========20210511 更新==================

#include <dirent.h>
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
void GetFileInDir(string dirName)
{
    DIR* Dir = NULL;
    struct dirent* file = NULL;
    if (dirName[dirName.size()-1] != '/')
    {
        dirName += "/";
    }
    if ((Dir = opendir(dirName.c_str())) == NULL)
    {
        cerr << "Can't open Directory" << endl;
        exit(1);
    }
    while (file = readdir(Dir))
    {
        //if the file is a normal file
        if (file->d_type == DT_REG)
        {
            cout << dirName + file->d_name << endl;
        }
        //if the file is a directory
        else if (file->d_type == DT_DIR && strcmp(file->d_name, ".") != 0 && strcmp(file->d_name, "..") != 0)
        {
            GetFileInDir(dirName + file->d_name);
        }
    }
}
int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        cerr << "Need Directory" << endl;
        exit(1);
    }
    string dir = argv[1];
    GetFileInDir(dir);
}

 

可以拿到目录下面所有目录下面的文件路径

void GetFileInDir(string dirName, vector<string> &v_path)
{
    DIR* Dir = NULL;
    struct dirent* file = NULL;
    if (dirName[dirName.size()-1] != '/')
    {
        dirName += "/";
    }
    if ((Dir = opendir(dirName.c_str())) == NULL)
    {
        cerr << "Can't open Directory" << endl;
        exit(1);
    }
    while (file = readdir(Dir))
    {
        //if the file is a normal file
        if (file->d_type == DT_REG)
        {
            v_path.push_back(dirName + file->d_name);
        }
            //if the file is a directory
        else if (file->d_type == DT_DIR && strcmp(file->d_name, ".") != 0 && strcmp(file->d_name, "..") != 0)
        {
            GetFileInDir(dirName + file->d_name,v_path);
        }
    }
}

 

  • 14
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
函数`_findfirst()`和函数`FindFirstFile()`是用于在指定目录查找文件的函数,它们在不同的编程环境中使用。 1. `_findfirst()`: - `_findfirst()`是C/C++运行时库(CRT)中的函数,通常在Windows环境下使用。 - `_findfirst()`的原型如下: ```c intptr_t _findfirst(const char* filespec, struct _finddata_t* fileinfo); ``` - `_findfirst()`的第一个参数`filespec`可以使用相对路径或绝对路径,但是如果使用相对路径,则相对路径是相对于当前工作目录。 - `_findfirst()`的查询结果存储在`struct _finddata_t`结构体中,包含了文件的各种属性信息。 2. `FindFirstFile()`: - `FindFirstFile()`是Windows API中的函数,通常在Windows环境下使用。 - `FindFirstFile()`的原型如下: ```c HANDLE FindFirstFile( LPCTSTR lpFileName, LPWIN32_FIND_DATA lpFindFileData ); ``` - `FindFirstFile()`的第一个参数`lpFileName`需要使用绝对路径。 - `FindFirstFile()`的查询结果存储在`WIN32_FIND_DATA`结构体中,包含了文件的各种属性信息。 两者的查询结果有以下区别: - `_findfirst()`返回一个型为`intptr_t`的句柄,可以通过该句柄进行后续的文件遍历操作,例如使用`_findnext()`函数获取下一个文件。 - `FindFirstFile()`返回一个型为`HANDLE`的句柄,可以通过该句柄进行后续的文件遍历操作,例如使用`FindNextFile()`函数获取下一个文件。 - `_findfirst()`的查询结果存储在`struct _finddata_t`结构体中。 - `FindFirstFile()`的查询结果存储在`WIN32_FIND_DATA`结构体中。 需要注意的是,两者的使用方式和参数略有差异,具体使用时要根据编程环境选择适当的函数,并根据函数要求提供正确的参数。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值