問題如題有目錄結構:./a/aa/aaa/1.txt./a/aa/aaa/2.txt./a/aa/aaa/3.txt./a/aa/bbb/1.txt./a/aa/bbb/2.txt./a/aa/bbb/3.txt./a/aa/ccc/1.txt./a/aa/ccc/2.txt./a/aa/ccc/3.txt我用的實現while循環下加嵌套函數。按上面目錄結構輸出正確結果應該為:文件數9個 目錄數6可我的程序結果為:文件數3個 目錄數4個(bbb ccc2個目錄及其下面的6個文件未統計完整代碼如下:#include <iostream>using namespace std;#include <sys/types.h>#include <dirent.h>#include <unistd.h>#include <sys/stat.h>#include <string.h>int Fn=0;int Dn=0;DIR* p_Dir = NULL;int count(char *);int main(int argc,char* argv[]){if(argc!=2){cout <<"Usage:<filename> DirName"<<endl;return -1;}p_Dir = opendir(argv[1]);if(NULL==p_Dir){cout <<"Can't find the Dir:"<<argv[1]<<endl;return -2;}else{closedir(p_Dir);}p_Dir=NULL;count(argv[1]);//函授調用cout <<"The director include: "<<Fn<<" files and "<<Dn<<" directors."<<endl;}//函數定義int count(char* s_dir){struct stat buf;struct dirent* p_Dirent = NULL;if(stat(s_dir,&buf)<0){cout << "stat error\n";return -2;}if(S_ISDIR(buf.st_mode)){if(NULL==(p_Dir = opendir(s_dir))){cout << "Open "<<s_dir<<" director failure."<<endl;return -1;}while(p_Dirent = readdir(p_Dir)){if('.'==(p_Dirent->d_name[0])) continue; char str[256];memset(str,0,256);strcpy(str,s_dir);strcat(str,"/");strcat(str,p_Dirent->d_name);cout <<"found dir: " <<str<<endl;count(str); //嵌套調用}Dn++;return 0;}else{Fn++;return 0;}}
添加回答
舉報
0/150
提交
取消