C++获取路径下的文件名
时间: 2023-10-09 20:14:16 浏览: 281
C++获取指定路径下的文件名的方法有多种。根据引用和引用提供的示例代码,可以使用`getFiles`函数来获取指定路径下的文件名。这个函数遍历给定路径下的文件,并将文件名存储在一个`std::vector<std::string>`中。以下是一个示例代码,展示如何使用`getFiles`函数来获取指定路径下的文件名:
```cpp
#include <iostream>
#include <vector>
#include <string>
#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)
continue;
else if (ptr->d_type == DT_REG) { // regular file
std::string strFile = path + "/" + ptr->d_name;
files.push_back(strFile);
}
}
closedir(dir);
}
int main() {
std::string path = "/your/path/to/directory";
std::vector<std::string> files;
getFiles(path, files);
for (const auto& file : files) {
std::cout << file << std::endl;
}
return 0;
}
```
这段代码会输出指定路径下的所有文件名。
阅读全文
相关推荐















