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

655Z技术栈 C/C++编程 7小时前 4

在C++中,你可以使用以下方法来获取文件夹下所有文件名:

  1. 使用opendirreaddir函数来打开和读取文件夹中的文件。
  2. 使用循环来遍历文件夹中的所有文件。
  3. 使用struct dirent结构体的d_name成员来获取文件的名字。

以下是一个示例程序,演示了如何获取文件夹下所有文件名:

#include <iostream> #include <dirent.h> #include <string> #include <vector> std::vector<std::string> getFilesInFolder(const std::string& folderPath) { std::vector<std::string> fileList; DIR* dir; struct dirent* entry; // 打开文件夹 dir = opendir(folderPath.c_str()); if (dir == nullptr) { return fileList; } // 读取文件夹中的文件 while ((entry = readdir(dir)) != nullptr) { // 忽略当前目录和上级目录 if (std::string(entry->d_name) == "." || std::string(entry->d_name) == "..") { continue; } // 将文件名添加到列表中 fileList.push_back(entry->d_name); } // 关闭文件夹 closedir(dir); return fileList; } int main() { std::string folderPath = "/path/to/folder"; std::vector<std::string> fileList = getFilesInFolder(folderPath); // 打印文件名 for (const auto& file : fileList) { std::cout << file << std::endl; } return 0; }

请将/path/to/folder替换为你要读取文件的文件夹的实际路径。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”