/* 编译: dir:dir.c gcc -o $@ $< */ #include <stdio.h> #include <string.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h>
int do_search_dir(char *path); int do_check_dir(char *fullpath, char* truefullpath); void usage(char *apps); int count = 0;
int main(int argc,char **argv) { char fullpath[1024]={0}; if(argc != 2) { usage(argv[0]); return -1; } if( -1 ==do_check_dir(argv[1], fullpath) ) return -1; do_search_dir(fullpath); printf("\nThe total number of files is %d in the directory [%s].\n\n", count , fullpath); return 0; }
//return -1 search fail //return 0 search ok int do_search_dir(char *path) { DIR *dir; struct dirent *s_dir; struct stat file_stat; char currfile[1024]={0}; int len = strlen(path); if(path[len-1] != '/') { path[len] = '/'; path[len+1] = 0; } printf("%s\n",path); if( (dir=opendir(path)) == NULL) { printf("opendir(path) error.\n"); return -1; } while((s_dir=readdir(dir))!=NULL) { if((strcmp(s_dir->d_name,".")==0)||(strcmp(s_dir->d_name,"..")==0)) continue; sprintf(currfile,"%s%s",path,s_dir->d_name); stat(currfile,&file_stat); if(S_ISDIR(file_stat.st_mode)) do_search_dir(currfile); else printf("%-32s\tOK\n",currfile); count++; // //添加针对此文件的操作 // } closedir(dir); return 0; }
void usage(char * apps) { printf("Directory to search for files.\n\n"); printf("Usage: %s dirpath\n\n",apps); }
//return -1 directory error //args: //input -->fullpath //output -->truefullpath int do_check_dir(char *fullpath, char* truefullpath) { DIR *dir; int pathlen, i ,k; if( (dir=opendir(fullpath)) == NULL) { printf("opendir fullpath error.\nMaybe dir error.\n"); return -1; } closedir(dir); pathlen = strlen(fullpath); if( pathlen-1 != 0) // 路径长度不为1 的目录 { if( fullpath[pathlen-1] == '/' ) // 最后字节是'/' { for(i=pathlen-1; i>=0 ; i--) { if( fullpath[i-1] != '/' && fullpath[i] == '/') break; } fullpath[i+1] = 0; } else // 最后字节不是'/' { fullpath[pathlen] = '/'; fullpath[pathlen+1] = 0; } } else // 路径长度为1 的目录 { if(fullpath[pathlen-1] != '/') { fullpath[pathlen] = '/'; fullpath[pathlen+1] = 0; } else fullpath[pathlen] = 0; } strcpy(truefullpath,fullpath); return 0; }
|