alt="linux copendir如何判断文件类型" />
在Linux中,copendir函数用于打开一个目录流,以便读取目录中的条目。要判断文件类型,可以使用readdir函数读取目录条目,并结合stat函数获取文件信息。以下是一个简单的示例,展示了如何使用这些函数判断文件类型:
#<span>include <stdio.h></span>#<span>include <stdlib.h></span>#<span>include <dirent.h></span>#<span>include <sys/stat.h></span>#<span>include <string.h></span>int main(<span>int argc, char *argv[])</span> { DIR *dir; <span>struct dirent *entry;</span> <span>struct stat file_stat;</span> if (argc != 2) { fprintf(stderr, "Usage: %s <directory>n", argv[0]); return EXIT_FAILURE; } dir = opendir(argv[1]); if (dir == NULL) { perror("opendir"); return EXIT_FAILURE; } while ((entry = readdir(dir)) != NULL) { // 跳过当前目录和上级目录的特殊条目 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 构建文件的完整路径 char file_path[PATH_MAX]; snprintf(file_path, sizeof(file_path), "%s/%s", argv[1], entry->d_name); // 获取文件信息 if (stat(file_path, &file_stat) == -1) { perror("stat"); continue; } // 判断文件类型 if (S_ISREG(file_stat.st_mode)) { printf("%s is a regular filen", entry->d_name); } else if (S_ISDIR(file_stat.st_mode)) { printf("%s is a directoryn", entry->d_name); } else if (S_ISCHR(file_stat.st_mode)) { printf("%s is a character devicen", entry->d_name); } else if (S_ISBLK(file_stat.st_mode)) { printf("%s is a block devicen", entry->d_name); } else if (S_ISFIFO(file_stat.st_mode)) { printf("%s is a FIFO (named pipe)n", entry->d_name); } else if (S_ISSOCK(file_stat.st_mode)) { printf("%s is a socketn", entry->d_name); } else { printf("%s is of unknown typen", entry->d_name); } } closedir(dir); return EXIT_SUCCESS;}
登录后复制
文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/659435.html