15 C++遍历某个文件夹下的文件

1 遍历所有的,包括文件夹套文件夹

#include<iostream>
#include<string>
#include<io.h>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;

void fileSearch(string path)
{
    long hFile = 0;
    /*
        _finddata_t  存储文件各种信息的结构体,<io.h>;
    */
    struct _finddata_t fileInfo;
    string pathName;
    /*
        \\* 表示符合的所有文件;
        没有找到即文件夹为空,退出;
        assign 表示把 pathName清空并置为path;
        append 表示在末尾加上字符串;
        c_str 返回一个const char* 的临时指针;
        _findfirst
            搜索与指定的文件名称匹配的第一个实例,若成功则返回第一个实例的句柄,否则返回-1L;
            函数原型:long _findfirst( char *filespec, struct _finddata_t *fileinfo );
    */
    if ( ( hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo) ) == -1)
        return ;

    do {
        cout << path+"\\"+fileInfo.name << endl;
        /*
            文件夹下有 . 和 .. 目录,不能进入搜索;
            _A_SUBDIR 表示文件夹属性;
        */
        if( strcmp(fileInfo.name,"..") && strcmp(fileInfo.name,".") && fileInfo.attrib==_A_SUBDIR )
            fileSearch(path+"\\"+fileInfo.name);
    } while ( _findnext(hFile, &fileInfo) == 0 );
    /*
        _findnext 搜索与_findfirst函数提供的文件名称匹配的下一个实例,若成功则返回0,否则返回-1 ;
        _findclose 结束查找;
    */
    _findclose(hFile);
    return ;
}
int main()
{
    string path="E:\\Git";
    fileSearch(path);

    system("pause");
    return 0;
}

  

 2 完整小例程

#include<iostream>
#include<io.h>
#include<vector>
#include<string>

int get_files(std::string fileFolderPath, std::string fileExtension, std::vector<std::string>&file)
{
	std::string fileFolder = fileFolderPath + "\\*" + fileExtension;
	std::string fileName;
	struct _finddata_t fileInfo;
	long long findResult = _findfirst(fileFolder.c_str(), &fileInfo);
	if (findResult == -1)
	{
		_findclose(findResult);
		return 0;
	}
	bool flag = 0;

	do
	{
		fileName = fileFolderPath + "\\" + fileInfo.name;
		if (fileInfo.attrib == _A_ARCH)
		{
			file.push_back(fileName);
		}
	} while (_findnext(findResult, &fileInfo) == 0);

	_findclose(findResult);
}

void find_file(std::string fileFolderPath, std::string fileFolderExtension)
{

	//所有xml数据
	std::cout << "\n输出当前目录下的所有"<< fileFolderExtension <<"格式的文件" << std::endl;
	std::vector<std::string> xml_files;
	std::string fileExtension_xml = fileFolderExtension;
	get_files(fileFolderPath, fileExtension_xml, xml_files);

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



}

int main()
{
	//查询文件夹
	std::string fileFolderPath = "F:\\dongdong\\外包\\4有可能\\体感交互\\代码\\4手部识别\\Project2";

	find_file(fileFolderPath,".xml");// 查找xml类型
	find_file(fileFolderPath, "");   // 查找所有类型 除了文件夹

	system("pause");
	return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/kekeoutlook/p/11919303.html
今日推荐