alt=”linux copendir如何判斷文件類型” />
在linux中,copendir函數(shù)用于打開(kāi)一個(gè)目錄流,以便讀取目錄中的條目。要判斷文件類型,可以使用readdir函數(shù)讀取目錄條目,并結(jié)合stat函數(shù)獲取文件信息。以下是一個(gè)簡(jiǎn)單的示例,展示了如何使用這些函數(shù)判斷文件類型:
#<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) { // 跳過(guò)當(dāng)前目錄和上級(jí)目錄的特殊條目 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // 構(gòu)建文件的完整路徑 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; }
這個(gè)示例程序接受一個(gè)目錄作為命令行參數(shù),然后使用opendir打開(kāi)目錄流。接著,它使用readdir函數(shù)遍歷目錄中的條目,并使用stat函數(shù)獲取每個(gè)條目的文件信息。最后,根據(jù)文件信息中的模式(st_mode),使用宏(如S_ISREG、S_ISDIR等)判斷文件類型,并輸出相應(yīng)的信息。
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END