Linux系統編程 --- 如何列出一個目錄下面的所有文件
linux平臺可以使用opendir函數來打開一個目錄,用readdir讀取目錄當中的一個entry(一個entry可以是子目錄,文件,軟硬鏈接等),如果需要讀取所有目錄下面的文件,需要使用while((entry = readdir(dp))) 來讀去每個entry,直到讀取的entry == NULL。
還有需要注意的就是目錄打開之后,需要自己關閉的,可以調用closedir(DIR*)來關閉,這個和文件fd的操作非常類似,不會的同學可以參考標準的stdio文件操作。
下面代碼是從wiki上面摘過來的, listdir扮演了打印指定目錄下面所有文件的功能,類似于linux命令"ls"的功能。
/************************************************************** * A simpler and shorter implementation of ls(1) * ls(1) is very similar to the DIR command on DOS and Windows. **************************************************************/ #include <stdio.h> #include <dirent.h> int listdir(const char *path) { struct dirent *entry; DIR *dp; dp = opendir(path); if (dp == NULL) { perror("opendir"); return -1; } while((entry = readdir(dp))) puts(entry->d_name); closedir(dp); return 0; } int main(int argc, char **argv) { int counter = 1; if (argc == 1) listdir("."); while (++counter <= argc) { printf("\nListing %s...\n", argv[counter-1]); listdir(argv[counter-1]); } return 0; }
全站熱搜