c/c++遞歸打印文件夾

調用linux的系統函數,實現tree的功能,遞歸打印文件夾
使用到得函數:

DIR *opendir(const char *name);       // 打開文件夾
struct dirent *readdir(DIR *dirp);    // 遍歷文件夾
int closedir(DIR *dirp);              // 關閉文件夾

代碼如下:

/**
 * 遞歸打印文件夾
 * @param filePath 要打印的文件路徑
 * @param space 當前文件夾的層次
 */
void printFileTree(string filePath, int space) {
    string currPath = filePath;     // 保存當前路徑
    DIR *dir = opendir(filePath.c_str());  // 打開當前文件夾
    if (dir == nullptr) return;                 // 如果文件夾為空,則退出
    dirent *dirTree;
    //  readdir函數讀取完當前文件後,會自動跳到下一個文件,如果讀取完畢,會返回nullptr
    while ((dirTree = readdir(dir))) {
        // 不打印. ..以及隱藏的文件
        if (dirTree->d_name[0] == '.' || strcmp(dirTree->d_name, "..") == 0) continue;  
        for (int i = 0; i < space; ++i) {           // 打印提示符
            if (i == space - 1) cout << "|---";
            else cout << "|   ";
        }
        cout << dirTree->d_name << endl;        //  打印當前文件名
        if (dirTree->d_type == DT_DIR) {
            printFileTree(currPath + '/' + dirTree->d_name, space + 1); // 如果是文件夾,則繼續遞歸
        }

    }
    closedir(dir);  // 關閉當前文件夾
}

結果展示

Tags: