Linux系统编程 --- 如何列出一个目录下面的所有文件
linux平台可以使用opendir函数来打开一个目录,用readdir读取目录当中的一个entry(一个entry可以是子目录,文件,软硬链接等),如果需要读取所有目录下面的文件,需要使用while((entry = readdir(dp))) 来读去每个entry,直到读取的entry == NULL。
还有需要注意的就是目录打开之后,需要自己关闭的,可以调用closedir(DIR*)来关闭,这个和文件fd的操作非常类似,不会的同学可以参考标准的stdio文件操作。
下面代码是从wiki上面摘过来的, listdir扮演了打印指定目录下面所有文件的功能,类似于linux命令"ls"的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | /************************************************************** * 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; } |