lseek详解

朱老师嵌入式核心课程笔记
lseek函数详解

  • lseek
    ① 对文件进行操作时,该文件是动态文件,动态文件在内存中的形态就是文件流的形式。
    ② 在动态文件中,通过文件指针来表征这个正在操作的位置,文件指针是vnode中的一个元素。
    ③ 该指针不能直接访问,Linux提供lseek函数访问这个文件指针。
    ④ 打开一个文件时,默认下,文件指针只想文件流的开始,这时候write是从文件开始位置写入的,write与read自带移动文件指针的功能,write写入n字节后,文件指针会自动往后移动n位。
    ⑤ man 2 lseek(lseek是一种文件读写的API)

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

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

    whence

SEEK_SETThe offset is set to offset bytes
SEEK_ENDThe offset is set to the size of the file plus offset bytes
SEEK_CURThe offset is set to its current

在读写文件时,写入文件后,需要用lseek将文件指针指向文件开始位置,否则会从文件最后位置开始读

  • 用lseek计算文件长度
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>


int cal_len(const char *pathname)
{
	int fd = -1;		// fd 就是file descriptor,文件描述符
	int ret = -1;
	
	// 第一步:打开文件
	fd = open(pathname, O_RDONLY);
	if (-1 == fd)		// 有时候也写成: (fd < 0)
	{
		//printf("\n");
		perror("文件打开错误");
		// return -1;
		return -1;
	}
	//else
	//{
		//printf("文件打开成功,fd = %d.\n", fd);
	//}
	
	// 此时文件指针指向文件开头
	// 我们用lseek将文件指针移动到末尾,然后返回值就是文件指针距离文件开头的偏移量,也就是文件的长度了
	ret = lseek(fd, 0, SEEK_END);
	
	return ret;
}

int main(int argc, char *argv[])
{
	int fd = -1;		// fd 就是file descriptor,文件描述符
	int ret = -1;
	
	if (argc != 2)
	{
		printf("usage: %s filename\n", argv[0]);
		_exit(-1);
	}

	printf("文件长度是:%d字节\n", cal_len(argv[1]));
	return 0;
}
  • 用lseek创建一个空洞文件
    ① 空洞文件就是这个文件有一段是空的;
    ② 普通文件中间不能有空,write文件时从前往后移动文件指针,依次写入;
    ③ 用lseek往后跳过一段,就形成空洞文件;
    ④ 空洞文件对多线程共同操作文件非常有用。需要创建一个很大文件时,从头开始依次创建时间很长,可以将文件分成多段,多个线程操作每个线程负责其中一段的写入。
 ret = lseek(fd, 10, SEEK_SET);
  • 14
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值