简介:代码备忘,使用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