亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

求教關于linux下統計當前目錄下的子目錄數(當前目錄)與其各子目錄下的文件數?具體如題!

求教關于linux下統計當前目錄下的子目錄數(當前目錄)與其各子目錄下的文件數?具體如題!

慕斯王 2021-06-21 18:14:13
問題如題有目錄結構:./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;}}
查看完整描述

2 回答

?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

顯然,你的程序在遞歸中未能如愿的返回,只能統計深度最深的一個目錄,檢查并修改之。

查看完整回答
反對 回復 2021-06-27
  • 2 回答
  • 0 關注
  • 524 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號