1. 程式人生 > >c++遍歷資料夾內所有檔案

c++遍歷資料夾內所有檔案

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

using namespace std;
char * filePath = "D:\\JPEGImages";

void getFiles(string path, vector<string>& files)
{
    //檔案控制代碼  
    long long hFile = 0;//這個地方需要特別注意,win10使用者必須用long long 型別,win7可以用long型別
    //檔案資訊  
    struct _finddata_t fileinfo;
    string p;
    if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
    {
        do
        {
            //如果是目錄,迭代之  
            //如果不是,加入列表  
            if ((fileinfo.attrib &  _A_SUBDIR))
            {
                if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
                    getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
            }
            else
            {
                files.push_back(p.assign(path).append("\\").append(fileinfo.name));
            }
        } while (_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
}

void main()
{
    
    vector<string> files;

    ////獲取該路徑下的所有檔案  
    getFiles(filePath, files);

    char str[30];
    int size = files.size();
    for (int i = 0; i < size; i++)
    {
        cout << files[i].c_str() << endl;
    }
}