读取文件属性_Linux程序设计

 

读取文件属性_Linux程序设计

作者:zs5u.com 文章来源:知识无忧网 点击数: 更新时间:2009-1-10 11:16:58
在对文件执行相应操作前,有必要读取该文件的属性,文件的属性一般由 struct file 数据结构的成员变量保存

该教程所属专题:[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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值