C++读取指定目录下的所有文件

简介:代码备忘,使用C++读取指定目录下的所有文件名,并存入vector向量
需要的头文件

#include <sys/types.h>
#include <dirent.h>

函数代码:
输入文件夹的路径和vector向量,返回vimgPath

void loadImagePath(string imgDirPath,vector<string> &vimgPath)
{

	DIR *pDir;
    struct dirent* ptr;
    if(!(pDir = opendir(imgDirPath.c_str())))
    {
        cout<<"Folder doesn't Exist!"<<endl;
        return;
    }

    while((ptr = readdir(pDir))!=0) 
    {
        if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0)
        {
            vimgPath.push_back(imgDirPath + "/" + ptr->d_name);
    	}
    }
    sort(vimgPath.begin(),vimgPath.end());

    closedir(pDir);
}

附完整代码:
源代码文件:

// createImgPath.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <string.h>
#include <algorithm>

#include <sys/types.h>
#include <dirent.h>

using namespace std;

void loadImagePath(string imgDirPath,vector<string> &vimgPath)
{

	DIR *pDir;
    struct dirent* ptr;
    if(!(pDir = opendir(imgDirPath.c_str())))
    {
        cout<<"Folder doesn't Exist!"<<endl;
        return;
    }

    while((ptr = readdir(pDir))!=0) 
    {
        if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0)
        {
            vimgPath.push_back(imgDirPath + "/" + ptr->d_name);
    	}
    }
    sort(vimgPath.begin(),vimgPath.end());

    closedir(pDir);
}

int main(int argc, char** argv)
{
    vector<string>vdataPath;
    string folderPath = string(argv[1]);
    string savePath = "imgPath.txt";

    // loda image path
    loadImagePath(folderPath,vdataPath);

    // open savePath
    ofstream fout;
    fout.open(savePath,ios::out|ios::app);
    if(!fout.is_open()){
        printf("Image Path : %s is wrrong.\r\n",savePath.c_str());
        exit(-1);
    }

    // save image path
    for(auto v:vdataPath)
        fout<<v<<endl;
    
    fout.close();

    return 0;
}

CMakeLists.txt文件

cmake_minimum_required(VERSION 3.10)
project(createImgPath)

add_executable(createImgPath createImgPath.cpp)

运行命令

cd build
// 目录Files_Folder末尾不加斜杠,生成的路径文件在build/
./createImgPath Files_Folder
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值