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]# ./