码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 查找文件夹下的文件

时间:2015-01-15 21:54:08      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:

#include <string>
#include <vector>
#include <cstring>
#include <cstdio>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>

using std::strcmp;
using std::string;
using std::vector;

#if __cplusplus < 201103L
	#define nullptr NULL
#endif

#define SEARCH_PATH_LENGTH 1024

/*
*	搜索一个文件夹下的符合条件的文件
*/
bool searchFile(const char* directory, vector<string>& files, const char* ext, int subdir_level)
{
	const char* dir_path = directory;

	DIR	*dir = nullptr;
	
	//打开文件夹
	if((dir = opendir(dir_path)) == nullptr)
	{
		return false;
	}
	
	struct dirent 	entry;
	struct dirent* 	result;
	struct stat		file_stat;
	
	char cur_name[SEARCH_PATH_LENGTH];
	
	//读取文件夹下的一个文件
	while(readdir_r(dir, &entry, &result) == 0 && result)
	{
		const char* name = entry.d_name;
		
		//忽略掉.和..
		if(strcmp(name, ".") == 0 || strcmp(name, "..") == 0)
			continue;
		
		//检查拼接路径
		int count = sprintf(cur_name, "%s", dir_path);
		
		count += sprintf(&cur_name[count], "%s%s", cur_name[count - 1] == ‘/‘ ? "" : "/", name);
		
		//获取文件的状态
		if(lstat(cur_name, &file_stat) != -1)
		{
			//文件是普通文件
			if(!S_ISDIR(file_stat.st_mode))
			{	
				const char* rf = strrchr(cur_name, ‘.‘);
				
				//检查文件的后缀名
				if(rf != nullptr && strcmp(rf + 1, ext) == 0)
					files.push_back(string(cur_name, count));
			}
			//文件是文件夹
			else if(subdir_level >= 0)
			{
				//递归获取下一层目录的文件
				searchFile(cur_name, files, subdir_level - 1);
			}
		}
	}
	closedir(dir);
	
	return true;
}

 

C++ 查找文件夹下的文件

标签:

原文地址:http://www.cnblogs.com/kalafina/p/4227202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!