一些文件函数操作
1 #include <iostream> 2 #include <sys/types.h> 3 #include <dirent.h> 4 #include <sys/stat.h> 5 #include <string.h> 6 7 using namespace std; 8 char *s1="jpg"; 9 char *s2="png"; 10 char *s3="bmp"; 11 /*************************** 12 * 函数功能: 遍历文件夹 13 * return: void 14 * @para folderPath: 文件夹路径 15 ***************************/ 16 void showDirStructure(char *folderPath) 17 { 18 /********** BEGIN **********/ 19 static int begins = 1; 20 if(begins){ 21 cout<<"+--"; 22 int spoint = -1; 23 int n = strlen(folderPath); 24 for(int i=0;i<n;i++){ 25 if(folderPath[i]=='/') 26 spoint = i; 27 } 28 spoint += 1; 29 cout<<(folderPath+spoint)<<endl; 30 begins = 0; 31 } 32 static int gs = 2; 33 DIR* point = opendir(folderPath); 34 dirent* readdirs = readdir(point); 35 while(readdirs!=NULL){ 36 if(readdirs->d_name[0]=='.'&&readdirs->d_name[1]==0){ 37 readdirs = readdir(point); 38 continue; 39 } 40 if(readdirs->d_name[0]=='.'&&readdirs->d_name[1]=='.'&&readdirs->d_name[2]==0){ 41 readdirs = readdir(point); 42 continue; 43 } 44 int check = 1; 45 int pointd = -1; 46 int n = strlen(readdirs->d_name); 47 for(int i=0;i<n;i++){ 48 if(readdirs->d_name[i]=='.') 49 pointd = i; 50 } 51 pointd+=1; 52 int okk = 0; 53 if(pointd!=0){ 54 if(strcmp((readdirs->d_name+pointd),s1)==0) 55 okk = 1; 56 if(strcmp((readdirs->d_name+pointd),s2)==0) 57 okk = 1; 58 if(strcmp((readdirs->d_name+pointd),s3)==0) 59 okk = 1; 60 } 61 struct stat buf; 62 char *s = new char[266]; 63 int i = 0; 64 while(folderPath[i]!=0) {s[i] = folderPath[i];i+=1;} 65 s[i]='/';i+=1; 66 int j = 0; 67 while(readdirs->d_name[j]!=0){s[i] = readdirs->d_name[j];i+=1;j+=1;} 68 s[i] = 0; 69 stat(s,&buf); 70 if(S_ISDIR(buf.st_mode)){ 71 for(int i=0;i<gs;i++) cout<<' '; 72 cout<<"+--"; 73 cout<<readdirs->d_name<<endl; 74 gs+=2; 75 showDirStructure(s); 76 gs-=2; 77 } 78 else if(okk){ 79 for(int i=0;i<gs;i++) cout<<' '; 80 cout<<"--"; 81 cout<<readdirs->d_name<<endl; 82 } 83 readdirs = readdir(point); 84 } 85 closedir(point); 86 /********** END **********/ 87 }