美文网首页
c++按顺序读取目录内文件

c++按顺序读取目录内文件

作者: this_is_for_u | 来源:发表于2019-05-06 20:27 被阅读0次

背景

按顺序读取目录内文件

之前使用C语言的opendir函数读取目录内文件,发现不是按照名字排序的,看解释返回的列表貌似是根据到某个存储节点的距离来排序的,所以找到了这个函数scandir。

代码

#include <dirent.h>
int scandir(const char *name, struct dirent ***namelist,int (*filter)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **));
int alphasort(const void *a, const void *b);
int versionsort(const void *a, const void *b);

param 1:目录的名字
param 2:返回的目录内经过某种排序的文件列表
param 3:某种过滤规则,自定义
param 4:某种排序规则,可以自定义,也有两个给定的
注意:这里第二个参数是内部malloc内存,需要在外部free掉

附上代码:

#include <iterator>
#include <iostream>
#include <vector>
#include <stdio.h>
#include <dirent.h>

using namespace std;


int fileNameFilter(const struct dirent *cur) {
    std::string str(cur->d_name);
    if (str.find(".bin") != std::string::npos) {
        return 1;
    }
    return 0;
}

std::vector<std::string> getDirBinsSortedPath(std::string dirPath) {
    struct dirent **namelist;
    std::vector<std::string> ret;
    int n = scandir(dirPath.c_str(), &namelist, fileNameFilter, alphasort);
    if (n < 0) {
        return ret;
    }
    for (int i = 0; i < n; ++i) {
        std::string filePath(namelist[i]->d_name);
        ret.push_back(filePath);
        free(namelist[i]);
    };
    free(namelist);
    return ret;
}

相关文章

  • c++按顺序读取目录内文件

    背景 按顺序读取目录内文件 之前使用C语言的opendir函数读取目录内文件,发现不是按照名字排序的,看解释返回的...

  • Unity视频读取

    视频单个读取StreamingAssets文件夹中的视频 视频多个按顺序读取StreamingAssets文件夹

  • Android中文件的读写操作

    一、读取assets目录下的文件 二、读取raw目录下的文件 三、读取手机存储文件(内置) 四、写入到手机存储(内...

  • 文件操作

    讲所有记录顺序的写入一个文件→顺序文件:一个有限字符构成的顺序字符流。C++标准库中:ifstream(读取),o...

  • jmeter随机读取CSV文件数据

    我们常用配置元件“CSV 数据文件设置”来读取CSV文件数据,读取结果往往是按顺序来读取的。如果需要随机来读取数据...

  • 文件操作

    打开方式 按行读取 大文件读写 ----按行 文件/目录的常用操作 os.path.isdir()判断是否位目录,...

  • Linux系统读取目录内文件顺序

    昨晚服务在发布的时候, 出现如下异常 Caused by: java.lang.NoSuchMethodError...

  • Python IO 流

    转载请注明出处 读文件 读取整个文件 分段读取 按行读取代码 按行读取 二进制读取 写文件 文本写出 追加文件 二...

  • cordova实现文件系统的读写

    1.获取Document目录 2.创建目录 3.获取文件 4.获取文件夹内所有文件 5.写入文件 6.读取文件内容...

  • php 常用文件操作

    读取目录下所有文件 创建目录所有文件 写入缓存 读取缓存

网友评论

      本文标题:c++按顺序读取目录内文件

      本文链接:https://www.haomeiwen.com/subject/kvfjoqtx.html