c++ 11 目錄流DIR,dirent使用


void GetFiles(const std::string& img_dir_path,std::vector<std::string> &img_file_paths)
{
    DIR* dir;
    if ((dir = opendir(img_dir_path.c_str())) == nullptr) {
        throw std::runtime_error("directory " + img_dir_path + " does not exist");
    }
    dirent* dp;
    for (dp = readdir(dir); dp != nullptr; dp = readdir(dir)) {
        const std::string img_file_name = dp->d_name;

    // 使用readdir讀取目錄中的所有文件 
    // 默認情況下,包括了'.'和'..'目錄文件
if (img_file_name == "." || img_file_name == "..") {
            continue;
        }
        img_file_paths.push_back(img_dir_path + "/" + img_file_name);
    }
    closedir(dir);

    std::sort(img_file_paths.begin(), img_file_paths.end());
}
  • 在上述代碼中,通過使用 DIR、dirent 數據結構和 opendir、readdir 函數,實現了對目錄及目錄中的文件進行操作的目的;
  • 結構體 dirent 中的成員 d_type 表示讀取的目錄中的文件的類型,d_name 表示讀取的目錄中的文件的名字。
    struct __dirstream
    {
        void *__fd;
        char *__data;
        int __entry_data;
        char *__ptr;
        int __entry_ptr;
        size_t __allocation;
        size_t __size;
        __libc_lock_define (, __lock)
    };
    typedef struct __dirstream DIR;

    函數 DIR *opendir(const char *pathname),即打開文件目錄,返回的就是指向DIR結構體的指針,而該指針由以下幾個函數使用:
    struct dirent *readdir(DIR *dp);//讀取到的文件名存儲在結構體dirent的d_name成員中

    void rewinddir(DIR *dp);

    int closedir(DIR *dp);

    long telldir(DIR *dp);

    void seekdir(DIR *dp,long loc);

    #include <dirent.h>
     
    struct dirent
    {
        long d_ino;               /* inode number 索引節點號 */
        off_t d_off;              /* offset to this dirent 在目錄文件中的偏移 */
        unsigned short d_reclen;  /* length of this d_name 文件名長 */
        unsigned char d_type;     /* the type of d_name 文件類型 */
        char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最長256字符 *

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM