Linux函数fstat说明

环境:Vmware Workstation;CentOS-6.4-x86_64

说明:

int fstat(int fd, struct stat *buf)

参数fd必须是用open调用返回的有效文件描述符。

使用stat获取文件信息。

第一个参数为文件描述符;第二个参数为结构体地址。

结构体stat说明:

struct stat {
              dev_t     st_dev;     /* ID of device containing file */设备ID,包含文件
              ino_t     st_ino;     /* inode number */索引节点
              mode_t    st_mode;    /* protection */
              nlink_t   st_nlink;   /* number of hard links */
              uid_t     st_uid;     /* user ID of owner */用户ID
              gid_t     st_gid;     /* group ID of owner */组ID
              dev_t     st_rdev;    /* device ID (if special file) */设备ID
              off_t     st_size;    /* total size, in bytes */文件大小
              blksize_t st_blksize; /* blocksize for filesystem I/O */
              blkcnt_t  st_blocks;  /* number of blocks allocated */
              time_t    st_atime;   /* time of last access */文件的建立时间
              time_t    st_mtime;   /* time of last modification */文件的修改时间
              time_t    st_ctime;   /* time of last status change */最后一次修改状态的时间
          };

使用:

1、得到文件描述符

2、创建结构体变量

3、传递结构体变量地址和文件描述符

4、通过结构体成员变量,获取指定文件信息

步骤:

1、创建并编写源文件main.c:

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

int main(int arg, char *args[])
{
	// 打开文件
	int fd = open("a.txt", O_RDONLY);
	// 定义一个结构体变量
	struct stat st;
	// 返回值为-1时,代表获取文件信息失败,打印提示信息
	// 第一个参数是文件描述符,第二个参数是结构体的地址
	if (fstat(fd, &st) == -1)
	{
		printf("message : %s\n", strerror(errno));
	}
	// 通过结构体得到文件的大小并输出
	// 64位操作系统中 off_t是一个无符号的长整型类型
	// off_t  32位操作系统是一个无符号的整数,64位操作系统是一个无符号的long
	printf("file size : %lu\n", st.st_size);
	close(fd);
	return 0;
}

2、创建并编写源文件makefile:

.SUFFIXES:.c .o

CC=gcc

SRCS=main.c
OBJS=$(SRCS:.c=.o)
EXEC=main

start: $(OBJS)
	$(CC) -o $(EXEC) $(OBJS)
	@echo "-----------------------------OK-----------------------"

.c.o:
	$(CC) -Wall -o $@ -c $<

clean:
	rm -rf $(EXEC) $(OBJS)

3、创建并编辑文件a.txt:

12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
4、编译并执行程序:

[negivup@negivup mycode]$ make
gcc -Wall -o main.o -c main.c
gcc -o main main.o
-----------------------------OK-----------------------
[negivup@negivup mycode]$ ./main
file size : 119

PS:根据传智播客视频学习整理得出。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值