目錄操作函數opendir、readdir和closedir


首先,明確一個類型DIR的含義:

#include <dirent.h>

DIR    A type representing a directory stream.

DIR是在目錄項格式頭文件dirent.h中定義的,它表示一個目錄流類型。

一、opendir - open a directory

SYNOPSIS
#include <sys/types.h>
#include <dirent.h>

DIR *opendir(const char *name);

DESCRIPTION

opendir函數打開一個與給定的目錄名name相對應的目錄流,並返回一個指向該目錄流的指針。打開后,該目錄流指向了目錄中的第一個目錄項。

RETURN VALUE

opendir函數,打開成功,返回指向目錄流的指針;打開失敗,則返回NULL,並設置相應的錯誤代碼errno。

二、readdir - read a directory

SYNOPSIS
#include <sys/types.h>

#include <dirent.h>

struct dirent *readdir(DIR *dir);

DESCRIPTION

readdir函數返回一個指向dirent結構體的指針,該結構體代表了由dir指向的目錄流中的下一個目錄項;如果讀到end-of-file或者出現了錯誤,那么返回NULL。

在Linux系統中,dirent結構體定義如下:

       struct dirent {
             ino_t          d_ino;       /* inode number */
             off_t          d_off;       /* offset to the next dirent */
             unsigned short d_reclen;    /* length of this record */
             unsigned char  d_type;      /* type of file */
             char           d_name[256]; /* filename */
         };

readdir函數返回的值會被后續調用的(針對同一目錄流的)readdir函數返回值所覆蓋。

RETURN VALUE

readdir函數,成功時返回一個指向dirent結構體的指針;失敗時或讀到end-of-file時,返回NULL,並且設置相應的錯誤代碼errno。

三、closedir - close a directory

SYNOPSIS
#include <sys/types.h>

#include <dirent.h>

int closedir(DIR *dir);

DESCRIPTION

closedir函數關閉與指針dir相聯系的目錄流。關閉后,目錄流描述符dir不再可用。

RETURN VALUE

closedir函數,成功時返回0;失敗是返回-1,並設置相應的錯誤代碼errno。

四、chdir, fchdir - change working directory

SYNOPSIS
#include <unistd.h>

int chdir(const char *path);
int fchdir(int fd);

DESCRIPTION

chdir函數改變當前工作目錄為path指定的目錄。

fchdir函數與chdir功能一樣,唯一的區別是fchdir所要改變成的工作目錄由打開的文件描述符指定。

RETURN VALUE

成功,返回0;失敗,返回-1,並設置相應的錯誤代碼errno。


免責聲明!

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



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