问题如题有目录结构:
./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;
}
}
长风秋雁
相关分类