linux目录统计编程,linux系统编程----统计一个目录下的普通文件个数
主要是為了統計linux系統下一個指定目錄下面的普通文件個數,運用目錄操作的一些函數,配合遞歸調用來實現該功能。
首先介紹一下函數原型:
打開一個空目錄
DIR *opendir(const char *name);
參數: 目錄名
返回值: 指向目錄的指針
讀目錄
struct dirent *readdir(DIR *dirp);
參數: opendir的返回值
返回值: 指向目錄的指針
關閉目錄
int closedir(DIR *dirp);
代碼實現:readfileNum.c
1 #include
2 #include
3 #include
4 #include
5 #include
6
7
8 int get_file_num(char*root)9 {10 int total = 0;11 DIR* dir =NULL;12 //打開目錄
13 dir =opendir(root);14 //循環從目錄中讀文件
15
16 char path[1024];17 //定義記錄目錄指針
18 struct dirent* ptr =NULL;19 while( (ptr = readdir(dir)) !=NULL)20 {21 //跳過. 和 ..
22 if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)23 {24 continue;25 }26 //判斷是不是目錄
27 if(ptr->d_type ==DT_DIR)28 {29 sprintf(path, "%s/%s", root, ptr->d_name);30 //遞歸讀目錄
31 total +=get_file_num(path);32 }33 //如果是普通文件
34 if(ptr->d_type ==DT_REG)35 {36 total ++;37 }38 }39 closedir(dir);40 returntotal;41 }42
43 int main(int argc, char*argv[])44 {45 if(argc < 2)46 {47 printf("./a.out path");48 exit(1);49 }50
51 int total = get_file_num(argv[1]);52 printf("%s has regfile number: %d\n", argv[1], total);53 return 0;54 }
效果展示:
原文:http://www.cnblogs.com/liunianshiwei/p/6045395.html
總結
以上是生活随笔為你收集整理的linux目录统计编程,linux系统编程----统计一个目录下的普通文件个数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux上的项目可以在windows,
- 下一篇: linux+dhcp服务的安装包,服务器