溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++中怎么遍歷目錄下的文件

發(fā)布時間:2021-08-12 16:49:50 來源:億速云 閱讀:152 作者:Leah 欄目:大數(shù)據(jù)

這篇文章給大家介紹C++中怎么遍歷目錄下的文件,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

先上代碼:

#include <iostream>

#include <dirent.h>

void print_dir(DIR *dir) {

    struct dirent *file;

    // 遍歷文件夾下的內(nèi)容

    while ((file = readdir(dir)) != NULL) {

        printf("文件位置=%ld ", telldir(dir));

        printf("子文件:%20s  ", file->d_name);

        printf("\n");

    }

}

int main(int argc, const char * argv[]) {

    const char *dirPATH = "/Users/ckend/Documents";

    DIR *dir = opendir(dirPATH);

    print_dir(dir);

    return 0;

}

需要用到的頭文件:"dirent.h"

需要用到的結(jié)構(gòu)及函數(shù):"struct dirent"

"readdir()"

"opendir()"

"telldir()"

一個個地來講解:

  1. dirent.h, 包含了許多關(guān)于目錄操作的函數(shù)或結(jié)構(gòu)的頭文件。

  2. readdir(),來自于dirent.h,在程序內(nèi)的語句:

    while ((file = readdir(dir)) != NULL) {}

    其作用是返回指向文件夾內(nèi)的文件的dirent結(jié)構(gòu)指針,它會逐一進(jìn)行檢查,直到?jīng)]有更多的文件而返回NULL為止。

  3. opendir(),同樣來自于dirent.h,其用于打開某個文件夾路徑,并返回這個文件夾的DIR*指針。

  4. telldir(), 也是來自于dirent.h,它可以獲得當(dāng)前指針位置,并返回這個位置。

  5. struct dirent, 這個結(jié)構(gòu)也是來自于dirent.其內(nèi)容如下(摘自參考文獻(xiàn)):


  6. struct dirent {ino_t          d_ino;       /* 在文件系統(tǒng)中的inode number */off_t          d_seekoff;   /* 與文件夾流的位置指針操作相關(guān) */unsigned short d_reclen;    /* 本記錄的數(shù)據(jù)長度 */unsigned char  d_type;      /* 當(dāng)前遍歷子項的文件類型:文件、文件夾、link、socket等 */char           d_name[256]; /* 當(dāng)前遍歷子項的文件名 */};

關(guān)于C++中怎么遍歷目錄下的文件就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI