查看帮助
$ man -k direct | grep read
$ man 3 opendir
$ man 3 readdir
$ man 3 closedir
实现思路:
打开目录,读取每一条记录(对应一个文件或子目录)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
void do_ls(char []);
int main(int ac, char * av[]) {
if (ac == 1) {
do_ls(".");
} else {
while (--ac) {
do_ls(* ++av);
}
}
return 0;
}
void do_ls(char dirname[]) {
DIR *dirp;
struct dirent *dir;
// 判断dirname是否存在
if ((dirp = opendir(dirname)) == NULL) {
printf("can't open %s\n", dirname);
return;
}
while((dir = readdir(dirp)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(dirp);
}