c语言使用lseek获取文件大小——Linux文件IO

一、lseek函数
1、头文件

 #include <sys/types.h>
 #include <unistd.h>

2、函数原型

off_t lseek(int fd, off_t offset, int whence);

功能:重新定位与该文件相关联的打开文件的偏移量
描述符fd到参数根据指令的偏移量
参数1:打开的文件描述符
参数2:偏移量
参数3:
1>SEEK_SET
The offset is set to offset bytes.(设置便宜字节)
2>SEEK_CUR
The offset is set to its current location plus offset bytes.(偏移量设置为其当前位置加上偏移字节)
3>SEEK_END
The offset is set to the size of the file plus offset bytes.(偏移量设置为文件的大小加上偏移字节)
返回值:成功完成后,lseek()返回测量得到的偏移位置
以字节为单位,从文件的开始。如果出现错误,则返回值(off_t) -1
设置errno来表示错误
二、程序demon

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


int get_file_size(const char *file_path)
{
    int fp = open(file_path, O_RDWR);//以读写的方式打开文件
    if(fp == -1) {
	   perror("open");
	}
    
	int len = lseek(fp, 0L, SEEK_END);
    close(fp);
	return  len;
}

int main(const int argc,const char *argv[])
{

	printf("file_size is %d\n",get_file_size(argv[1]));
	return 0;
}

运行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值