牛骨文教育服务平台(让学习变的简单)
博文笔记

C++ 遍历文件夹下所有的文件

创建时间:2017-03-29 投稿人: 浏览次数:573

windows下和linux下遍历目录下所有的文件信息,这里暂时不处理子目录的情况,如需处理子目录里的文件,只需要递归一下就好了。

#include<iostream>
#include<io.h>
#include<vector>
#include<assert.h>
#include <dirent.h>
using namespace std;
//linux
void getAllFileFromDirectory(string path, vector<string> &file) {
        DIR *dp;
        struct dirent *dirp;
        if ((dp = opendir(path.c_str())) == NULL) {
            assert("can"t open dir");
        }
        while ((dirp = readdir(dp)) != NULL) {
            files.push_back(fileInfo.name);
            cout << dirp->d_name << endl;
        }
        closedir(dp);
        return ;
}

//windows
void getAllFileListFromDirectory(string path,vector<string> &files) {
    long lf = 0;
    _finddata_t fileInfo;
    cout << "enter in" << endl;
    if ((lf = _findfirst(path.c_str(), &fileInfo)) == -1) {
        assert("no file exists!");
    }
    while (_findnext(lf, &fileInfo) == 0) {
        files.push_back(fileInfo.name);
        cout << fileInfo.name<<endl;
    }
    _findclose(lf);
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。