该教程所属专题:[Linux高级程序设计专题] 通过这里可以进入该专题教程,学习井井有条。
本文由 知识无忧网 首发,转载请保留此信息!
6.2.1 读取文件属性
1.读取文件属性函数
在对文件执行相应操作前,有必要读取该文件的属性,文件的属性一般由 struct file 数据
结构的成员变量保存。Linux 读取文件属性的函数 stat 定义如下。
//come from /usr/include/sys/stat.h
/* Get file attributes for FILE and put them in BUF. */
extern int stat (__const char *__restrict __file, struct stat *__restrict __buf) __THROW
__nonnull ((1, 2));
此函数第一个参数为欲读取状态的文件,可以使用绝对路径或相对路径,第二个参数为
读取的文件状态存放的临时数据结构 buf。
struct stat 数据结构定义如下:
come from /usr/include/asm/stat.h
struct stat {
unsigned short st_dev; //设备号
unsigned short __pad1;
unsigned long st_ino; //节点
unsigned short st_mode; //模式
unsigned short st_nlink; //连接
unsigned short st_uid; //用户 ID
unsigned short st_gid; //组 ID
unsigned short st_rdev; //设备类型
unsigned short __pad2;
unsigned long st_size; //
unsigned long st_blksize; //块大小
unsigned long st_blocks; //块数量
unsigned long st_atime; //最后一次访问时间
unsigned long __unused1;
unsigned long st_mtime; //最后一次修改时间
unsigned long __unused2;
unsigned long st_ctime; 属性时间
unsigned long __unused3;
unsigned long __unused4;
unsigned long __unused5;
}
如果要读取已打开的文件流的状态,可以使用 fstat 函数,其声明如下:
//come from /usr/include/sys/stat.h
//Get file attributes for the file, device, pipe, or socket that file descriptor
//FD is open on and put them in BUF*/
extern int fstat (int __fd, struct stat *__buf) __THROW __nonnull ((2));
此函数的参数与 stat 函数的参数相同。
对于连接文件,则可以使用 lstat 函数来读取。
/* Get file attributes about FILE and put them in BUF. If FILE is a symbolic link, do
not follow it. */
extern int lstat (__const char *__restrict __file, struct stat *__restrict __buf) __THROW
__nonnull ((1, 2));
2.读取文件属性示例程序
下面是一个使用 stat()函数读取文件属性的示例程序。此程序将输出文件的读写权限,与
ls –l 命令输入的文件权限类似。其源代码如下:
[root@localhost yangzongde]# cat stat_example.c
#include
#include
#include
#include
#include
#define N_BITS 3
int main(int argc,char *argv[])
{
uns