在Linux中,readdir
函數是用于遍歷目錄的主要方法。它定義在dirent.h
頭文件中。以下是一些使用readdir
遍歷目錄的技巧和示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 1;
}
readdir
讀取目錄中的條目:struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 處理目錄條目
}
closedir(dir);
在循環中,你可以處理每個目錄條目。例如,你可以打印文件名、檢查文件類型等。
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
你可以使用stat
函數獲取文件的詳細信息,然后根據文件類型進行處理。
struct dirent *entry;
struct stat file_stat;
while ((entry = readdir(dir)) != NULL) {
char path[PATH_MAX];
snprintf(path, sizeof(path), "%s/%s", dir->d_name, entry->d_name);
if (stat(path, &file_stat) == -1) {
perror("stat");
continue;
}
if (S_ISREG(file_stat.st_mode)) {
printf("Regular file: %s\n", entry->d_name);
} else if (S_ISDIR(file_stat.st_mode)) {
printf("Directory: %s\n", entry->d_name);
} else {
printf("Other: %s\n", entry->d_name);
}
}
在遍歷目錄時,可能會遇到錯誤。確保檢查opendir
、readdir
和stat
等函數的返回值,并在出現錯誤時進行適當的處理。
這些技巧應該足以幫助你使用readdir
函數遍歷Linux目錄。根據你的需求,你可以對這些示例進行修改和擴展。