《linux c 下如何获得目录下的文件数目.pdf》由会员分享,可在线阅读,更多相关《linux c 下如何获得目录下的文件数目.pdf(2页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、linux c 下如何获得目录下的文件数目int main(int argc,char*argv)DIR*pdir;struct dirent*pdirent;struct stat f_ftime;int fcnt;/*文件数目统计*/pdir=opendir(./);if(pdir=NULL)return(-1);fcnt=0;for(pdirent=readdir(pdir);pdirent!=NULL;pdirent=readdir(pdir)if(strcmp(pdirent-d_name,.)=0|strcmp(pdirent-d_name,.)=0)continue;if(sta
2、t(pdirent-d_name,&f_ftime)!=0)return-1;if(S_ISDIR(f_ftime.st_mode)continue;/*子目录跳过*/fcnt+;printf(文件:%sn,pdirent-d_name);printf(文件总数%dn,fcnt);closedir(pdir);return 0;#include#include#include#include#include void printdir(char*dir,int depth)DIR*dp;struct dirent*entry;struct stat statbuf;if(dp=opendir(
3、dir)=NULL)fprintf(stderr,cannot open directory:%sn,dir);return;chdir(dir);while(entry=readdir(dp)!=NULL)lstat(entry-d_name,&statbuf);if(S_ISDIR(statbuf.st_mode)/*/*Found a directory,but ignore.and.*/if(strcmp(.,entry-d_name)=0|strcmp(.,entry-d_name)=0)continue;printf(%*s%s/n,depth,entry-d_name);/*/*
4、Recurse at a new indent level*/printdir(entry-d_name,depth+4);else printf(%*s%sn,depth,entry-d_name);chdir(.);closedir(dp);/*/*Now we move onto the main function.*/int main(int argc,char*argv)char*topdir,pwd2=.;if(argc!=2)topdir=pwd;elsetopdir=argv1;printf(Directory scan of%sn,topdir);printdir(topdir,0);printf(done.n);exit(0);