Linux:目錄函數(shù)

  • 打開一個目錄

    函數(shù)原型 DIR *opendir(const char *name)
    DIR *fopendir(int fd)
    頭文件 #include <sys/types.h>
    #include <dirent.h>
    參數(shù) name:目錄名稱
    fd:要打開目錄的文件描述符
    返回值 成功:返回一個指向目錄流的指針
    失敗:返回空指針NULL
  • 關(guān)閉一個目錄

    函數(shù)原型 int closedir(DIR *dirp)
    頭文件 #include <sys/types.h>
    #include <dirnet.h>
    參數(shù) dirp:要關(guān)閉的目錄的目錄流結(jié)構(gòu)體
    返回值 成功:返回0
    失?。悍祷?code>-1
  • 獲取一個目錄流的文件描述符

    函數(shù)原型 int dirfd(DIR *dirp)
    頭文件 #include <sys/types.h>
    #include <dirnet.h>
    參數(shù) dirp:要獲取文件描述符的目錄流
    返回值 成功:返回一個非負(fù)的文件描述符
    失?。悍祷?code>-1
  • 讀取一個目錄

    函數(shù)原型 struct dirent *readdir(DIR *dirp);
    頭文件 #include <dirent.h>
    參數(shù) dirp:要讀取的目錄的目錄流
    返回值 成功:返回一個dirnet結(jié)構(gòu)體的指針或者NULL, NULL意味著到了流的結(jié)束
    失?。悍祷?code>NULL,并且設(shè)置想用的errno

    結(jié)構(gòu)體dirent的內(nèi)容如下:

    struct dirent {
        ino_t          d_ino;       /* Inode number */
        off_t          d_off;       /* Not an offset; see below */
        unsigned short d_reclen;    /* Length of this record */
        unsigned char  d_type;      /* Type of file; not supported
                                                by all filesystem types */
        char           d_name[256]; /* Null-terminated filename */
    };
    
    • d_ino:文件(目錄)的inode數(shù)。

    • d_off:該數(shù)據(jù)的值跟telldir返回的值相同,其含義為在目錄流的當(dāng)前位置。盡管它是一個off_t 類型,我們應(yīng)該認(rèn)為這個值對我們是不透明的,不要做任何的假設(shè)。

    • d_reclen:當(dāng)前記錄的大?。ㄒ宰止?jié)為單位)。它可能不匹配上面結(jié)構(gòu)體定義的大小。

    • d_type:表示文件類型。使用此字段可以省去調(diào)用lstat來獲取文件的類型。

      • DT_BLK :塊設(shè)備
      • DT_CHR :字符設(shè)備
      • DT_DIR :目錄
      • DT_FIFO : 管道
      • DT_LNK : 符號鏈接
      • DT_REG : 常規(guī)文件
      • DT_SOCK : socket文件
      • DT_UNKNOWN : 文件類型無法確認(rèn)
    • d_name:文件名稱,以NULL結(jié)尾。

  • 重置目錄流
    函數(shù)原型 voi rewinddir(DIR *dirp)
    頭文件 #include <sys/types.h>
    #include <dirnet.h>
    參數(shù) dirp:目錄流
    返回值
  • 掃描一個目錄來匹配

    函數(shù)原型 int scandir(const char *dirp, struct dirent ***namelist, int (*filter)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **));
    頭文件 #include <dirent.h>
    參數(shù) dirp:目錄名
    namelist:掃描目錄的結(jié)果
    filter:過濾函數(shù),對掃描結(jié)果進(jìn)行過濾
    compar:用于排序的比較函數(shù)
    返回值 成功:返回選擇的文件的數(shù)量
    失?。?code>-1
  • 設(shè)置下一次readdir()調(diào)用的位置

    函數(shù)原型 void seekdir(DIR *dirp, long loc);
    頭文件 #include <dirent.h>
    參數(shù) dirp:要操作的目錄結(jié)構(gòu)體的指針
    loc:要設(shè)置的位置
    返回值 void
  • 返回當(dāng)前readdir()讀到的位置

    函數(shù)原型 long telldir(DIR *dirp);
    頭文件 #include <dirent.h>
    參數(shù) dirp:要操作的目錄
    返回值 成功:目錄流的當(dāng)前位置
    失敗:-1
?著作權(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)容