1. 程式人生 > >【C/C++檔案處理系列】struct stat 結構體定義

【C/C++檔案處理系列】struct stat 結構體定義

獲取檔案狀態的函式 stat fstat lstat 都與struct stat 有關。函式原型如下,都定義在   sys/stat.h 中,原型如下

  int stat(const char *path, struct stat *buf);
  int fstat(int fd, struct stat *buf);
  int lstat(const char *path, struct stat *buf);
函式實現稍後整理。

###

struct stat的定義部分找了很久,最終在看 linux 系統命令  stat的手冊中,找到了

SEE ALSO
       stat(2)

       The  full documentation for stat is maintained as a Texinfo manual.  

 man  2 stat ,得到 struct stat 的詳細說明,介紹了 stat()  lstat()及 fstat() 的基本功能及struct stat的定義。

These  functions  return information about a file.  No permissions are required on the file itself, but — in
       the case of stat() and lstat() — execute (search) permission is required on all of the directories  in  path
       that lead to the file.

       stat() stats the file pointed to by path and fills in buf.

       lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not
       the file that it refers to.

       fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.

       All of these system calls return a stat structure, which contains the following fields:

           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 file system I/O */
               blkcnt_t  st_blocks;  /* number of 512B 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 */
           };

           
st_dev: 描述檔案歸屬的裝置
st_rdev:描述檔案inode 所代表的裝置
st_size:檔案位元組數,如果是符號連結,則表示路徑大小。
st_blocks :分配給該檔案的塊數,即512位元組單位。不考慮空洞情況
st_blksize :檔案系統的首先塊大小。
st_atime:上次訪問時間,訪問檔案的操作會改變該值 
st_mtime:上次修改時間, 
st_ctime:上次狀態改變的時間,對檔案的讀寫將改變該值。
###

linux 系統中 stat 命令 與ls 的預設執行如下

$
$stat stat.h
  File: `stat.h'
  Size: 16815     	Blocks: 40         IO Block: 4096   regular file
Device: 801h/2049d	Inode: 845263      Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2015-01-28 18:09:35.000000000 +0800
Modify: 2015-01-28 18:09:35.000000000 +0800
Change: 2015-03-14 04:18:17.000000000 +0800
$
$ls -l stat.h 
-rw-r--r-- 1 root root 16815 Jan 28  2015 stat.h
$