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

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值