Linux学习:读取目录内容 (目录名和类型)和递归统计指定目录下普通文件个数练习
生活随笔
收集整理的這篇文章主要介紹了
Linux学习:读取目录内容 (目录名和类型)和递归统计指定目录下普通文件个数练习
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、讀取目錄內容
#include <stdio.h> #include <unistd.h> #include <dirent.h> #include <sys/types.h> int main(int argc,char *argv[]) {if( argc < 2 ){printf( "./a.out filename" );return -1;}DIR *pDir = opendir(argv[1]);if( pDir == NULL ){perror( "opendir err" );return -1;}//循環讀取 struct dirent *pDent = NULL;while( ( pDent = readdir(pDir) ) ){//進入循環,意味著 pDen 非空,代表讀到目錄的內容printf("%s -%d\n", pDent->d_name, pDent->d_type);}//關閉目錄closedir(pDir);return 0; }二、遞歸統計指定目錄下普通文件個數
//遍歷目錄,統計普通文件個數 #include <stdio.h> #include <unistd.h> #include <dirent.h> #include <sys/types.h> #include <string.h> int count = 0; // 記錄文件個數 全局變量 int filecount(const char *path) // 自定義函數 // 參數:目錄名 {DIR *pDir = opendir(path); // 打開目錄,獲得目錄信息if(pDir == NULL){perror("opendir err ");return -1;}// 循環讀取struct dirent *pDent = NULL; // 傳出參數while( ( pDent = readdir(pDir) ) ){// 進入循環,意味著 pDen 非空,代表讀到目錄的內容if(pDent->d_type == DT_REG){count++; // 如果是普通文件,計數加1}else if(pDent->d_type == DT_DIR){// 如果是目錄文件if(strcmp(pDent->d_name,".") == 0 || strcmp(pDent->d_name,"..") == 0){continue; // 過濾 . 和 ..}// 能否傳遞pent->d_name? 不可以!d_name只是文件名,不帶路徑char strNewPath[1024] = {0};sprintf(strNewPath,"%s/%s", path, pDent->d_name); // 拼接子目錄相對路徑filecount(strNewPath); // 遞歸調用,繼續計數}}closedir(pDir); // 關閉目錄return 0; } int main(int argc,char *argv[]) {if(argc < 2){printf("./a.out filename\n");return -1;}filecount(argv[1]); // 自定義函數:傳入目錄名(路徑),普通文件個數賦值給全局變量countprintf("file count is %d\n", count);return 0; }總結
以上是生活随笔為你收集整理的Linux学习:读取目录内容 (目录名和类型)和递归统计指定目录下普通文件个数练习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux学习:目录遍历函数
- 下一篇: Linux学习:文件描述符相关函数