linux属性函数
1 stat函数
1.1 函数描述
获取文件的属性
int stat(const char *pathname, struct stat *statbuf);
函数接收两个参数
pathname
: 传入文件的路径statbuf
: 传出参数,是一个结构体,里面包含文件的各种属性
返回值
- 正确返回0
- 错误返回-1, 设置errno
这里stat
结构体定义如下:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* Inode number */
mode_t st_mode; /* File type and mode */
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; /* Block size for filesystem I/O */
blkcnt_t st_blocks; /* Number of 512B blocks allocated */
/* Since Linux 2.6, the kernel supports nanosecond
precision for the following timestamp fields.
For the details before Linux 2.6, see NOTES. */
struct timespec st_atim; /* Time of last access */
struct timespec st_mtim; /* Time of last modification */
struct timespec st_ctim; /* Time of last status change */
#define st_atime st_atim.tv_sec /* Backward compatibility */
#define st_mtime st_mtim.tv_sec
#define st_ctime st_ctim.tv_sec
};
1.2 函数的使用
打印文件的属性
0 #include <stdio.h>
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5
6 int main(int argc, char *argv[])
7 {
8 if(argc <2) //判断参数,需要传入一个文件名
9 {
10 printf("need arg.\n");
11 exit(-1);
12 }
13
14 struct stat statbuf; //定义stat结构体
15 stat(argv[1], &statbuf); //调用stat函数,获取文件属性
16 printf("st_mode: %o\n",statbuf.st_mode); //打印文件属性
17 printf("st_uid : %u\n",statbuf.st_uid);
18 printf("st_gid : %u\n",statbuf.st_gid);
19