#include #include#include#include
void dir_scan(char *path, char *file);int count = 0;int main(int argc, char *argv[])
{structstat s;if(argc != 2){
printf("one direction requried\n");
exit(1);
}if(lstat(argv[1], &s) < 0){
printf("lstat error\n");
exit(2);
}//判断一个路径是否是目录
if(!S_ISDIR(s.st_mode)){
printf("%s is not a direction name\n", argv[1]);
exit(3);
}
dir_scan("", argv[1]);
printf("total: %d files\n", count);
exit(0);
}void dir_scan(char *path, char *file)
{structstat s;
DIR*dir;struct dirent *dt;char dirname[50];
memset(dirname,0, 50*sizeof(char));
strcpy(dirname, path);if(lstat(file, &s) < 0){
printf("lstat error\n");
}if(S_ISDIR(s.st_mode)){
strcpy(dirname+strlen(dirname), file);
strcpy(dirname+strlen(dirname), "/");if((dir = opendir(file)) ==NULL){
printf("opendir %s/%s error\n");
exit(4);
}if(chdir(file) < 0) {
printf("chdir error\n");
exit(5);
}while((dt = readdir(dir)) !=NULL){if(dt->d_name[0] == ‘.‘){continue;
}
dir_scan(dirname, dt->d_name);
}if(chdir("..") < 0){
printf("chdir error\n");
exit(6);
}
}else{
printf("%s%s\n", dirname, file);
count++;
}
}
linux c 下如何获得目录下的文件数目。int main(int argc, char **argv)
{
DIR*pdir;struct dirent *pdirent;structstat 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(stat(pdirent->d_name,&f_ftime)!=0) return -1;if(S_ISDIR(f_ftime.st_mode)) continue; /*子目录跳过*/fcnt++;
printf("文件:%s\n",pdirent->d_name);
}
printf("文件总数%d\n",fcnt);
closedir(pdir);return 0;
}
#include#include#include#include#include
void printdir(char *dir, intdepth)
{
DIR*dp;struct dirent *entry;structstat 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)) {/**//*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);/**//*Recurse at a new indent level*/printdir(entry-> d_name,depth+4);
}else printf( "%*s%s\n",depth, " ",entry->d_name);
}
chdir("..");
closedir(dp);
}/**//*Now we move onto the main function.*/
int main(int argc, char*argv[])
{char *topdir, pwd[2]= ".";if (argc != 2)
topdir=pwd;elsetopdir=argv[1];
printf("Directory scan of %s\n",topdir);
printdir(topdir,0);
printf("done.\n");
exit(0);
}