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

猜你喜欢

转载自blog.csdn.net/qiqzhang/article/details/83506886