在 Linux 下,使用 opendir()
函數打開目錄時,如果成功,它會返回一個指向 DIR
結構的指針。如果失敗,它會返回 NULL
。為了判斷 opendir()
是否成功,你可以檢查其返回值是否為 NULL
。
以下是一個簡單的示例:
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("/path/to/directory");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
在這個示例中,我們首先嘗試使用 opendir()
打開一個目錄。然后,我們檢查 dir
是否為 NULL
。如果是,我們使用 perror()
函數打印錯誤信息,并返回 1 表示出錯。如果 opendir()
成功,我們繼續讀取目錄中的條目并關閉目錄。