c++怎么获取文件夹下的所有文件名
你可以使用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
函数使用opendir
和readdir
来遍历指定文件夹下的所有文件名,并将文件名存储在一个字符串向量中。然后,在main
函数中调用getFilesInFolder
函数来获取文件夹下的所有文件名,并使用循环打印每个文件名。
请确保在代码中替换folderPath
为你要获取文件名的文件夹的实际路径。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:云服务器的硬盘性能因素有哪些 下一篇:海外服务器的数据备份方式有哪些
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。