entry = readdir()后,如何看entry是目录还是文件
时间: 2024-03-25 08:37:04 浏览: 21
在 Linux 系统中,可以通过判断 `entry->d_type` 的值来确定 `entry` 是目录还是文件。如果 `entry->d_type` 的值为 `DT_DIR`,则 `entry` 是目录;如果 `entry->d_type` 的值为 `DT_REG`,则 `entry` 是文件。具体的代码可以参考下面的示例:
```c
#include <sys/types.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
if ((dir = opendir(argv[1])) == NULL) {
perror("opendir error");
return -1;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_DIR) {
printf("%s is a directory\n", entry->d_name);
} else if (entry->d_type == DT_REG) {
printf("%s is a regular file\n", entry->d_name);
} else {
printf("%s is unknown\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
```
在上面的示例中,我们打开一个目录,并遍历目录中的所有文件和子目录,并通过 `entry->d_type` 判断它们是目录还是文件。注意,不是所有的文件系统都支持 `d_type`,在某些文件系统中,`d_type` 的值始终为 `DT_UNKNOWN`,此时不能通过 `d_type` 判断 `entry` 的类型,需要使用其他方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)