- #include <unistd.h>
- #include <stdio.h>
- #include <dirent.h>
-
- #include <string.h>
- #include <sys/stat.h>
- #include <stdlib.h>
-
- void printdir(char *dir, int depth){
- DIR *dp; //DIR 结构包含在dirent.h里头
- struct dirent *entry;
- struct stat statbuf;
-
- if((dp = opendir(dir)) == NULL){
- //opendir打开dir参数所指向的目录并建立一个目录流,成功则返回一个指向DIR结构的指针
- fprintf(stderr, "cannot open directory: %s\n", dir);
- //失败则向标准错误流写入错误信息
- return;
- }
- chdir(dir);//切换目录
- while((entry = readdir(dp)) != NULL) {
- //readdir函数将返回一个指向dirent结构体的指针
- //dirent结构中包含文件的inode节点号(ino_t d_ino)以及文件的名字(char d_name[])
- lstat(entry->d_name, &statbuf);
- //lstat函数将文件状态信息放到参数statbuf里头
- if(S_ISDIR(statbuf.st_mode)) {
- if(strcmp(".",entry->d_name) == 0 ||
- strcmp("..",entry->d_name) == 0)
- continue;
- printf("%*s%s/\n",depth,"",entry->d_name);
- printdir(entry->d_name,depth+4);
- }
- else printf("%*s%s\n",depth,"",entry->d_name);
- }
- chdir("..");
- closedir(dp);
- }
-
- int main(){
- printf("Directory scan of /home:\n");
- printdir("/home",0);
- printf("done.\n");
-
- exit(0);
- }
目录扫描printfdir
最新推荐文章于 2021-05-20 17:29:17 发布