linux c++11遍历文件夹
时间: 2023-10-20 17:33:57 浏览: 115
要在Linux C中遍历文件夹,可以使用dirent.h头文件中的相关函数来实现。下面是一个示例代码:
```c
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void TraverseFolder(const char* folderPath) {
DIR* dir = opendir(folderPath);
if (dir == NULL) {
printf("Folder doesn't exist!\n");
return;
}
struct dirent* entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
}
int main() {
const char* folderPath = "./imgs";
TraverseFolder(folderPath);
return 0;
}
```
这段代码使用opendir函数打开指定的文件夹路径,然后使用readdir函数遍历文件夹中的文件和子文件夹。在遍历的过程中,排除了当前目录"."和上层目录".."。你可以根据需求修改代码,将文件名存储到一个向量或其他数据结构中,以便后续处理。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Linux-C++-遍历指定文件夹路径下的文件列表并将路径写到txt文件](https://download.csdn.net/download/lobster_wang/10438535)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [Linux 下 C++ 遍历文件夹下的文件名](https://blog.csdn.net/weixin_38419133/article/details/103561532)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文