#include <sys/stat.h>
文件狀態,
是unix/linux系統定義文件狀態所在的偽標准頭文件。
含有類型與函數:
dev_t st_dev Device ID of device containing file.
ino_t st_ino File serial number.
mode_t st_mode Mode of file (see below).
nlink_t st_nlink Number of hard links to the file.
uid_t st_uid User ID of file.
gid_t st_gid Group ID of file.
dev_t st_rdev Device ID (if file is character or block special).
off_t st_size For regular files, the file size in bytes.
For symbolic links, the length in bytes of the
pathname contained in the symbolic link.
For a shared memory object, the length in bytes.
For a typed memory object, the length in bytes.
For other file types, the use of this field is
unspecified.
time_t st_atime Time of last access.
time_t st_mtime Time of last data modification.
time_t st_ctime Time of last status change.
int chmod(const char *, mode_t);
int fchmod(int, mode_t);
int fstat(int, struct stat *);
int lstat(const char *restrict, struct stat *restrict);
int mkdir(const char *, mode_t);
int mkfifo(const char *, mode_t);
int mknod(const char *, mode_t, dev_t);
int stat(const char *restrict, struct stat *restrict);
mode_t umask(mode_t);
使用stat函數最多的可能是ls-l命令,用其可以獲得有關一個文件的所有信息。
一般頭文件在/usr/include下面,這里是標准C程序頭文件,如果你的頭文件前加了 <sys/*>,那說明這是系統調用函數頭文件,其在/usr/include/sys下面。
函數都是獲取文件(普通文件,目錄,管道,socket,字符,塊()的屬性。函數原型#include <sys/stat.h>
int stat(const char *restrict pathname, struct stat *restrict buf);提供文件名字,獲取文件對應屬性。
int fstat(int filedes, struct stat *buf);通過文件描述符獲取文件對應的屬性。
int lstat(const char *restrict pathname, struct stat *restrict buf);連接文件描述命,獲取文件屬性。
文件對應的屬性struct stat {
mode_t st_mode; //文件對應的模式,文件,目錄等
ino_t st_ino; //inode節點號
dev_t st_dev; //設備號碼
dev_t st_rdev; //特殊設備號碼
nlink_t st_nlink; //文件的連接數
uid_t st_uid; //文件所有者
gid_t st_gid; //文件所有者對應的組
off_t st_size; //普通文件,對應的文件字節數
time_t st_atime; //文件最后被訪問的時間
time_t st_mtime; //文件內容最后被修改的時間
time_t st_ctime; //文件狀態改變時間
blksize_t st_blksize; //文件內容對應的塊大小
blkcnt_t st_blocks; //偉建內容對應的塊數量
};
示例:
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main() {
struct stat buf;
stat("/etc/hosts", &buf);
printf("/etc/hosts file size = %d\n", buf.st_size);
}