一、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;
}
运行结果