C++ 遍歷某個文件夾下所有文件


#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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM