linux程序设计目录扫描实验问题
来源:互联网 发布:全站仪数据导出 编辑:程序博客网 时间:2024/06/03 18:18
源代码:
#include<unistd.h>#include<stdio.h>#include<dirent.h>#include<string.h>#include<sys/stat.h>#include<stdlib.h>void printfdir(char *dir,int depth){ DIR *dp; struct dirent *entry; struct stat statbuf; if((dp=opendir(dir))==NULL) { fprintf(stderr,"cannot open directory: %s\n",dir); return; } chdir(dir); while ((entry=readdir(dp))!=NULL) { lstat(entry->d_name,&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); printfdir(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"); printfdir("/home/xgl/Code",0); printf("done.\n"); exit(0);}
问题:为什么while循环后要切换到上层目录?递归完成后不是会自动回到上层么。将31行注释后发现虽然能输出上层目录包含的目录或文件,但均被识别为目录,且包含的目录不会进行递归。
原因:递归后程序确实跳回上层,所以能输出上层目录包括的目录和文件,但是由于lstat函数传入的只是文件或目录的相对路径,如果不将当前程序扫描目录带回上一级的话,它只会在下层扫描该文件名,但下层是没有该文件或目录的。将传给lstat函数的地址改为绝对路径就没问题了(一点不方便)
代码如下:
#include<unistd.h>#include<stdio.h>#include<dirent.h>#include<string.h>#include<sys/stat.h>#include<stdlib.h>void printfdir(char *dir,int depth){ DIR *dp; struct dirent *entry; struct stat statbuf; char pwd[256]; if((dp=opendir(dir))==NULL) { fprintf(stderr,"cannot open directory: %s\n",dir); return; } chdir(dir); while ((entry=readdir(dp))!=NULL) { sprintf(pwd,"%s/%s",dir,entry->d_name); lstat(pwd,&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); printfdir(pwd,depth+4);} else printf("%*s%s\n",depth," ",entry->d_name); } // chdir(".."); closedir(dp);}int main(){ printf("Directory scan of /home:\n"); printfdir("/home/xgl/Code",0); printf("done.\n"); exit(0);}
0 0
- linux程序设计目录扫描实验问题
- linux目录扫描
- Linux文件操作-->扫描目录
- linux c 扫描文件目录
- Linux下多线程程序设计实验
- Linux系统上对目录进行扫描
- Linux中实现一个目录扫描程序
- linux下目录扫描的实现
- 腾讯面试:Linux下如何扫描目录
- linux扫描目录下所有文件
- Linux程序设计(Linux目录结构)
- Linux程序设计(Linux目录权限)
- Linux——实验一:Shell程序设计
- 《Linux内核与程序设计》实验学习笔记
- 扫描目录
- UNIX程序设计实验三 目录树的遍历
- linux程序设计文件目录操作读书笔记
- Linux下的目录扫描操作函数使用实践
- CSDN终于改进了编辑器啦!!!
- 历届试题 矩阵翻硬币 蓝桥杯 大数开方 大数相乘
- newInstance()和new ()的区别
- RCU讲解
- A Simple Problem with Integers(线段树之区间点的成段更新)
- linux程序设计目录扫描实验问题
- IdHTTPServer完成websocket服务端编写
- 13.2.1 访问世界银行的数据
- 正则表达式(候选项)
- Cas(02)——部署Cas Server
- gcc工具的切换
- 第四讲项目1—求两数之和(界面友好)
- Deepin挂载内存盘
- 欢迎使用CSDN-markdown编辑器