温馨提示×

c++怎么获取文件夹下的所有文件名

c++
小亿
116
2023-09-19 15:36:37
栏目: 编程语言

你可以使用C++的文件流和目录流来获取文件夹下的所有文件名。下面是一个示例代码:

#include <iostream>
#include <fstream>
#include <dirent.h>
#include <vector>
std::vector<std::string> getFilesInFolder(const std::string& folderPath) {
std::vector<std::string> fileNames;
DIR* dir;
struct dirent* entry;
if ((dir = opendir(folderPath.c_str())) != nullptr) {
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_type == DT_REG) {
fileNames.push_back(entry->d_name);
}
}
closedir(dir);
}
return fileNames;
}
int main() {
std::string folderPath = "path/to/folder";
std::vector<std::string> files = getFilesInFolder(folderPath);
for (const std::string& file : files) {
std::cout << file << std::endl;
}
return 0;
}

在上面的代码中,getFilesInFolder函数使用opendirreaddir来遍历指定文件夹下的所有文件名,并将文件名存储在一个字符串向量中。然后,在main函数中调用getFilesInFolder函数来获取文件夹下的所有文件名,并使用循环打印每个文件名。

请确保在代码中替换folderPath为你要获取文件名的文件夹的实际路径。

0