檔案屬性函式stat/fstat/lstat
stat,lstat,fstat1 函式都是獲取檔案(普通檔案,目錄,管道,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 <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
int main(int argc, char *argv[])
{
struct stat buf;
// 檢查引數
if (argc != 2) {
printf("Usage: my_stat <filename>/n");
exit(0);
}
// 獲取檔案屬性
if ( stat(argv[1], &buf)
perror("stat:");
exit(1);
}
// 打印出檔案屬性
printf("device is: %d/n", buf.st_dev);
printf("inode is: %d/n", buf.st_ino);
printf("mode is: %o/n", buf.st_mode);
printf("number of hard links is: %d/n", buf.st_nlink);
printf("user ID of owner is: %d/n", buf.st_uid);
printf("group ID of owner is: %d/n", buf.st_gid);
printf("device type (if inode device) is: %d/n", buf.st_rdev);
printf("total size, in bytes is: %d/n", buf.st_size);
printf(" blocksize for filesystem I/O is: %d/n", buf.st_blksize);
printf("number of blocks allocated is: %d/n", buf.st_blocks);
printf("time of last access is: %s", ctime(&buf.st_atime));
printf("time of last modification is: %s", ctime(&buf.st_mtime));
printf("time of last change is: %s", ctime(&buf.st_ctime));
return 0;
}