还有需要注意的就是目录打开之后,需要自己关闭的,可以调用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;
- }