Linux C/C++遍歷目錄及目錄下文件

背景

某項目中需要對指定目錄下的所有文本文件加密,于是需要搜索指定目錄下所有的文本文件。

要想搜索,先要能夠遍歷指定目錄下所有文件,并且支持對遞歸子目錄的遍歷。

分析

我們知道,許多操作系統(tǒng)中的目錄結(jié)構(gòu)都是使用樹結(jié)構(gòu)。

使用遞歸的方法定義樹是比較容易的。一棵樹地一些節(jié)點的集合。
這個集合可以為空,若非空,則樹由樹根和0個或者多個非空的子樹組成。
子樹中的根都被來自樹根的一條有向的邊所連接。
因此,可以很自然地想到使用遞歸的方式來遍歷指定的目錄。

除了遞歸,還可以考慮使用非遞歸方式實現(xiàn),這樣效率會更高,但也更復(fù)雜。

遞歸實現(xiàn)

思路:遞歸實現(xiàn)較簡單,對于一個給定的目錄,遍歷目錄下所有文件,有三種情況:

本目錄或父目錄,忽略
普通文件,輸出
目錄,遞歸調(diào)用
源代碼如下:

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>

#define MAX_PATH_LEN (256)

static void trave_dir(char* path) {
    DIR *d = NULL;
    struct dirent *dp = NULL; /* readdir函數(shù)的返回值就存放在這個結(jié)構(gòu)體中 */
    struct stat st;    
    char p[MAX_PATH_LEN] = {0};
    
    if(stat(path, &st) < 0 || !S_ISDIR(st.st_mode)) {
        printf("invalid path: %s\n", path);
        return;
    }

    if(!(d = opendir(path))) {
        printf("opendir[%s] error: %m\n", path);
        return;
    }

    while((dp = readdir(d)) != NULL) {
        /* 把當前目錄.,上一級目錄..及隱藏文件都去掉,避免死循環(huán)遍歷目錄 */
        if((!strncmp(dp->d_name, ".", 1)) || (!strncmp(dp->d_name, "..", 2)))
            continue;

        snprintf(p, sizeof(p) - 1, "%s/%s", path, dp->d_name);
        stat(p, &st);
        if(!S_ISDIR(st.st_mode)) {
            printf("%s\n", dp->d_name);
        } else {
            printf("%s/\n", dp->d_name);
            trave_dir(p);
        }
    }
    closedir(d);

    return;
}

int main(int argc, char **argv)
{   
    char *path = NULL;
 
    if (argc != 2) {
        printf("Usage: %s [dir]\n", argv[0]);
        printf("use DEFAULT option: %s .\n", argv[0]);
        printf("-------------------------------------------\n");
        path = "./";
    } else {
        path = argv[1];
    }

    trave_dir(path);

    return 0;
}

非遞歸實現(xiàn)

非遞歸實現(xiàn)的方法會有很多,一個思路是,每次遍歷目錄時,把查找到的文件直接輸出,目錄則保存,用于下次遍歷目錄下的內(nèi)容。

此處使用鏈表實現(xiàn),結(jié)構(gòu)體用于存儲目錄路徑和下一個目錄,遍歷目錄的過程同上,代碼如下:

#include <stdio.h>
#include <dirent.h> 
#include <stdlib.h> 
#include <string.h>
#include <unistd.h>
#include <error.h>
#include <sys/stat.h>  

#define MAX_FILE_NAME_LEN 256

typedef struct foldernode_t {
  char *path;                // point to foldername or filename path
  struct foldernode_t *next;   
} foldernode;

static void travel_files(char *path)
{
    DIR *dir;
    struct dirent *ptr;
    char foldername[MAX_FILE_NAME_LEN] = {0};
    char folderpath[MAX_FILE_NAME_LEN] = {0};

    foldernode *folderstart;
    folderstart = calloc(1, sizeof(foldernode));/* ignore err case */
    folderstart->path = calloc(1, MAX_FILE_NAME_LEN + 1); 
    strncpy(folderstart->path, path, MAX_FILE_NAME_LEN);
    folderstart->next = NULL;

    foldernode *folderfirst = folderstart; /* use to search */
    foldernode *folderlast = folderstart; /* use to add foldernode */
    foldernode *oldfirst = NULL;

    while(folderfirst != NULL) {
        printf("dir=%s\n", folderfirst->path);
        if ((dir = opendir(folderfirst->path)) != NULL) {
            while ((ptr = readdir(dir)) != NULL) {
                if(strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) {
                    continue;  
                } else if (ptr->d_type == DT_REG) { /* regular file */
                    printf("%s\n", ptr->d_name);
                } else if (ptr->d_type == DT_DIR) { /* dir */
                    bzero(foldername, sizeof(foldername));
                    bzero(folderpath, sizeof(folderpath));
                    strncpy(foldername, ptr->d_name, sizeof(foldername));
                    snprintf(folderpath, sizeof(folderpath), "%s/%s", folderfirst->path , foldername);
                    printf("%s\n", folderpath);
                    
                    foldernode *foldernew;
                    foldernew = calloc(1, sizeof(foldernode));
                    foldernew->path = calloc(1, MAX_FILE_NAME_LEN + 1); 
                    strncpy(foldernew->path, folderpath, MAX_FILE_NAME_LEN);
                    foldernew->next = NULL;
                    
                    folderlast->next = foldernew;
                    folderlast = foldernew;

                }
            }
        } else {
            printf("opendir[%s] error: %m\n", folderfirst->path);
            return;
        }
        oldfirst = folderfirst;
        folderfirst = folderfirst->next; // change folderfirst point to next foldernode
        if (oldfirst) {
            if (oldfirst->path) {
                free(oldfirst->path);
                oldfirst->path = NULL;
            }
            free(oldfirst);
            oldfirst = NULL;
        }
        closedir(dir);
    }
}

int main(int argc,char **argv)
{
    if (argc != 2) {
        printf("Usage: %s path\n", argv[0]);
        return 0;
    }

    travel_files(argv[1]);

    return 0;
}

總體

對目錄的遍歷是比較基本的功能,對于理解文件系統(tǒng)和數(shù)據(jù)結(jié)構(gòu)有一定的幫助。

也可以參考bash命令中l(wèi)s的源碼,增加對命令行參數(shù)的支持,實現(xiàn)更加復(fù)雜的功能。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容