1. 程式人生 > >c/c++ 獲取目錄下檔案列表

c/c++ 獲取目錄下檔案列表

經過測試 Windows 和 Linux版本都可以執行。
windows版本

標頭檔案:io.h
關鍵函式:_findfirst、_findnext
關鍵結構體:_finddata_t

struct _finddata_t
{
    unsigned attrib;
                //_A_ARCH(存檔)
                //_A_HIDDEN(隱藏)
                //_A_NORMAL(正常)
                //_A_RDONLY(只讀)
                //_A_SUBDIR(資料夾)
                //_A_SYSTEM(系統)
    time_t time_create;
                //建立日期
    time_t time_access;
                //最後訪問日期
    time_t time_write;
                //最後修改日期
    _fsize_t size;
                //檔案大小
    char name[_MAX_FNAME];
                //檔名, _MAX_FNAME表示檔名最大長度
};

   

程式碼

#include <iostream>
#include <string>
#include <io.h>
using namespace std;
void dir(string path)
{
    long hFile = 0;
    struct _finddata_t fileInfo;
    string pathName, exdName;
                // \\* 代表要遍歷所有的型別,如改成\\*.jpg表示遍歷jpg型別檔案
    if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -1) {
        return;
    }
    do
    {
                //判斷檔案的屬性是資料夾還是檔案
        cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR ? "[folder]" : "[file]") << endl;
    } while (_findnext(hFile, &fileInfo) == 0);
    _findclose(hFile);
    return;
}
int main()
{
                //要遍歷的目錄
    string path = "E:\\intel_tuyoji_pic\\群賢";
    dir(path);
    system("pause");
    return 0;
}

linux版本

#include<iostream>
#include<string>
#include<dirent.h>
using namespace std;
int main()
{
    string dirname;
    DIR *dp;
    struct dirent *dirp;
    cout << "Please input a directory: ";
    cin >> dirname;
    if((dp = opendir(dirname.c_str())) == NULL)
    {
        cout << "Can't open " << dirname << endl;
    }
    while((dirp = readdir(dp)) != NULL)
    {
        cout << dirp->d_name << endl;
    }
    closedir(dp);
    return 0;
}