擷取檔案屬性資訊之stat、fstat和lstat

來源:互聯網
上載者:User

UNIX檔案系統是目錄和檔案組成的一種階層。檔案屬性是指檔案類型(是普通檔案還是目錄)、檔案大小、檔案所有者、檔案許可權以及檔案最後的修改時間等。stat和fstat函數可擷取包含檔案所有屬性的一個資訊結構(可使用man fstat查看這兩個函數的協助資訊)。

stat, fstat, lstat – 擷取檔案屬性資訊

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>
       #include <unistd.h>

int stat(const char *path, struct stat *buf);
       int fstat(int filedes, struct stat *buf);
       int lstat(const char *path, struct stat *buf);

DESCRIPTION

這些函數擷取檔案屬性資訊。對檔案本身不需要任何許可權,但是stat和lstat,需要對到達該檔案的路徑上的所有目錄具有可執行許可權才可擷取該檔案屬性資訊。

stat函數統計由path指向的檔案的屬性資訊並將該屬性資訊結構存入buf中;

lstat函數與stat函數功能完全一樣,不同的是,如果它的檔案路徑path是一個軟串連,那麼統計的是該軟串連的資訊,而不是該連結指向的檔案的屬性資訊。

fstat函數與stat函數功能也完全一樣,不同的是,該函數所統計的檔案是由檔案描述符filedes指定的。

上述三個函數成功返回0,失敗返回-1.

通過上面這三個函數都可以擷取到檔案的一個stat結構體,該結構體定義如下:

struct stat {
             dev_t     st_dev;     /* ID of device containing file */
             ino_t     st_ino;     /* inode number */
             mode_t    st_mode;    /* protection */
             nlink_t   st_nlink;   /* number of hard links */
             uid_t     st_uid;     /* user ID of owner */
             gid_t     st_gid;     /* group ID of owner */
             dev_t     st_rdev;    /* device ID (if special file) */
             off_t     st_size;    /* total size, in bytes */
             blksize_t st_blksize; /* blocksize for filesystem I/O */
             blkcnt_t  st_blocks;  /* number of blocks allocated */
             time_t    st_atime;   /* time of last access */
             time_t    st_mtime;   /* time of last modification */
             time_t    st_ctime;   /* time of last status change */
         };

簡單嘗試著用一下stat函數擷取檔案屬性資訊:

<stdio.h><sys/types.h><sys/stat.h><unistd.h> main(, & 

運行結果:

[root@localhost test]# ./

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.