windows和linux获取文件夹内容的一种方法

windows:

使用头文件:<io.h>、<direct.h>

关键函数:_findfirst、_findnext

关键结构体:_finddata_t

	_finddata_t	fileinfo;
	intptr_t hFile;
	string root;
	root.assign(Path);//文件夹绝对路径
	int len = root.length();
	
	if ( !IsEndObliqueLine(Path) )//路径的结尾不是‘\’
	{
		root.append("\\");
	}
	root.append("*");//路径下的所有文件

	hFile = _findfirst(root.c_str(), &fileinfo);
	if ( -1 == hFile)
	{
		assert(false);
		return;
	}
	strcpy(m_CurrentPath, Path);//保存到m_CurrentPath
	//清空之前Path的信息
	FilesPathVector.clear();//自定义的保存信息的容器
	do //保存信息
	{
		LISTCMD_INFO TmpDirInfo = {0};
		TransFileInfo(fileinfo, TmpDirInfo);
		FilesPathVector.push_back(TmpDirInfo);
	}while(_findnext(hFile, &fileinfo)   ==   0);

linux:

使用头文件: <dirent.h>、 <sys/types.h>、<sys/stat.h>

关键函数:readdir、lstat

关键结构体:dirent

	DIR *dir;
	if ( !(dir = opendir(Path)) )
	{
		assert(false);
		return;
	}
    	strcpy(m_CurrentPath, Path);//保存到m_CurrentPath
	struct dirent *d_ent;
	char fullpath[128];
	FilesPathVector.clear();
	while ( (d_ent = readdir(dir)) != NULL )
	{
		struct stat file_stat;
		//if ( strncmp(d_ent->d_name, ".", 1) == 0 )
		//{
		//	continue;	// 忽略"."目录
		//}
		memset(fullpath, '\0', sizeof(fullpath));
		strcpy( fullpath,  Path);
		if ( !strcmp(fullpath, "/") )
		{
			fullpath[0] = '\0';
		}
		strcat(fullpath, "/");
		strcat(fullpath, d_ent->d_name);
		if ( lstat(fullpath, &file_stat) < 0 )
		{
			assert(false);
			return;
		}
		//保存信息到自己的数据结构,在函数外面保存文件名
		LISTCMD_INFO TmpDirInfo = {0};
		strcpy(TmpDirInfo.cFileName, d_ent->d_name);
		TransFileInfo(&file_stat, TmpDirInfo);
		FilesPathVector.push_back(TmpDirInfo);
	}
	closedir(dir);


值得注意的是,此种方法windows的路径分隔是用'\',而linux用'/',使用时多少有点不便。

如果有其他更好得方法,欢迎交流!

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值