C语言遍历文件夹下的所有文件
时间: 2023-08-29 09:12:17 浏览: 312
可以使用 dirent.h 头文件中的 readdir() 函数和 stat() 函数实现。以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
void traverseDir(char *dir) {
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp = opendir(dir)) == NULL) {
fprintf(stderr, "Cannot open directory: %s\n", dir);
return;
}
chdir(dir);
while ((entry = readdir(dp)) != NULL) {
lstat(entry->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0) {
continue;
}
printf("Directory: %s\n", entry->d_name);
traverseDir(entry->d_name);
} else {
printf("File: %s\n", entry->d_name);
}
}
chdir("..");
closedir(dp);
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s directory_name\n", argv[0]);
exit(1);
}
traverseDir(argv[1]);
return 0;
}
```
传入要遍历的目录路径作为参数,通过 opendir() 函数打开目录,然后使用 readdir() 函数遍历目录下的所有文件夹和文件,使用 stat() 函数获取每个文件的信息,并根据 st_mode 判断是文件夹还是文件,进而递归遍历文件夹中的文件。最后使用 closedir() 函数关闭目录。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)