“佳人猶唱醉翁詞,四十三年如電抹,”——(北宋) 蘇軾 《木蘭花·次歐公西湖韻》
昨天又在網路上摘抄了一段工具類的代碼,因為以后可能還會用到,所以簡單記錄一下,使用C++獲取指定目錄中的所有檔案名,這里不包括該目錄下的子目錄的檔案,如果需要包括的話可以在網上再搜一搜,有很多可以實作這個功能的代碼,話不多說,直接上代碼:
#include <stdio.h>
#include <string.h>
#include <dirent.h>
void getFiles(std::string path, std::vector<std::string> &files) {
DIR *dir;
struct dirent *ptr;
if ((dir = opendir(path.c_str())) == NULL) {
perror("Open dir error...");
return;
}
while ((ptr = readdir(dir)) != NULL) {
if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) ///current dir OR parrent dir
continue;
else if (ptr->d_type == 8) ///file
{
std::string strFile;
strFile = path;
strFile += "/";
strFile += ptr->d_name;
files.push_back(strFile);
} else {
continue;
}
}
closedir(dir);
}
這個函式呼叫也是非常簡單,直接給出路徑,呼叫函式方法獲取檔案名就可以:
#include <iostream>
int main() {
std::string path = "/home/dong/data";
std::vector<std::string> files;
getFiles(path, files);
for (int i = 0; i < files.size(); ++i) {
std::cout << files[i] << std::endl;
}
std::cout << "Hello, World!" << std::endl;
return 0;
}
這個功能比較簡單,所以也就簡單記錄一下!
參考:
1、C++獲取指定路徑下的所有檔案(windows和Linux版)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/206538.html
標籤:其他
