c遍历文件夹
时间: 2023-07-29 17:08:04 浏览: 36
您好,以下是C语言遍历文件夹的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
/**
* 遍历文件夹
*
* @param path 文件夹路径
*/
void traverseDirectory(char *path) {
DIR *dir;
struct dirent *ptr;
char base[1000];
if ((dir = opendir(path)) == NULL) {
perror("Open dir error...");
exit(1);
}
while ((ptr = readdir(dir)) != NULL) {
if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) {
continue;
} else if (ptr->d_type == DT_DIR) {
sprintf(base, "%s/%s", path, ptr->d_name);
traverseDirectory(base);
} else if (ptr->d_type == DT_REG) {
printf("%s/%s\n", path, ptr->d_name);
}
}
closedir(dir);
}
int main() {
char path[1000];
printf("Please input directory path: ");
scanf("%s", path);
traverseDirectory(path);
return 0;
}
```
该程序使用了C标准库中的`<dirent.h>`头文件,通过`opendir()`函数打开指定路径的目录,并通过`readdir()`函数读取目录中的文件和子目录。遇到子目录时,使用递归的方式继续遍历子目录。遇到文件时,直接输出文件路径。`closedir()`函数用于关闭目录。