問題如題有目錄結(jié)構(gòu):./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我用的實(shí)現(xiàn)while循環(huán)下加嵌套函數(shù)。按上面目錄結(jié)構(gòu)輸出正確結(jié)果應(yīng)該為:文件數(shù)9個(gè) 目錄數(shù)6可我的程序結(jié)果為:文件數(shù)3個(gè) 目錄數(shù)4個(gè)(bbb ccc2個(gè)目錄及其下面的6個(gè)文件未統(tǒng)計(jì)完整代碼如下:#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]);//函授調(diào)用cout <<"The director include: "<<Fn<<" files and "<<Dn<<" directors."<<endl;}//函數(shù)定義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); //嵌套調(diào)用}Dn++;return 0;}else{Fn++;return 0;}}
2 回答
長風(fēng)秋雁
TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
顯然,你的程序在遞歸中未能如愿的返回,只能統(tǒng)計(jì)深度最深的一個(gè)目錄,檢查并修改之。
添加回答
舉報(bào)
0/150
提交
取消
