文件“光标”位置

这篇博客介绍了Linux系统中用于控制文件读写位置的lseek函数,包括其函数原型、参数说明及使用方法。通过示例展示了如何将读写位置移动到文件开头、文件尾以及获取当前文件位置。此外,还提供了代码解决文件读取失败问题和计算文件大小的实例。
摘要由CSDN通过智能技术生成

光标位置手册

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6ZW_56m6Ou-8ieWklemGiQ==,size_20,color_FFFFFF,t_70,g_se,x_16

相关说明

头文件:#include <sys/types.h>    #include <unistd.h>

定义函数:off_t lseek(int fildes, off_t offset, int whence);

函数说明:
每一个已打开的文件都有一个读写位置, 当打开文件时通常其读写位置是指向文件开头, 若是以附加的方式打开文件(如O_APPEND), 则读写位置会指向文件尾. 当read()或write()时, 读写位置会随之增加,lseek()便是用来控制该文件的读写位置. 参数fildes 为已打开的文件描述词, 参数offset 为根据参数whence来移动读写位置的位移数.


参数 whence 为下列其中一种:
    SEEK_SET 参数offset 即为新的读写位置.
    SEEK_CUR 以目前的读写位置往后增加offset 个位移量.
    SEEK_END 将读写位置指向文件尾后再增加offset 个位移量. 当whence 值为SEEK_CUR 或
    SEEK_END 时, 参数offet 允许负值的出现.

下列是教特别的使用方式:
1) 欲将读写位置移到文件开头时:lseek(int fildes, 0, SEEK_SET);
2) 欲将读写位置移到文件尾时:lseek(int fildes, 0, SEEK_END);
3) 想要取得目前文件位置时:lseek(int fildes, 0, SEEK_CUR);

返回值:当调用成功时则返回目前的读写位置, 也就是距离文件开头多少个字节. 若有错误则返回-1, errno 会存放错误代码. 

代码解决文件读取失败问题

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
	int fd;
	char *buf = "chenglong henshuai?";

	fd = open("./file1",O_RDWR);
	
	if(fd == -1){
		printf("open file1 failed\n");
		fd = open("./file1",O_RDWR|O_CREAT,0600);
		if(fd > 0){
			printf("create file1\n");
		}
	}
	printf("fd = %d\n",fd);
	
	int n_write = write(fd,buf,strlen(buf));
//	write(fd,buf,sizeof(buf));
	
	if(n_write != -1){
		printf("write %d byte to file1\n",n_write);
	}	

//off_t lseek(int fd, off_t offset, int whence);
	
	char *readBuf;
	readBuf = (char *)malloc(sizeof(char )*n_write + 1);	
	lseek(fd,-19,SEEK_CUR);    //光标移动
	
	int n_read = read(fd,readBuf,n_write);
	
	printf("read %d,context:%s\n",n_read,readBuf);
	
	close(fd);

	return 0;
}
fd = 3
write 19 byte to file1
read 19,context:chenglong henshuai?

用光标计算文件大小

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
        int fd;
        char *buf = "chenglong henshuai?";

        fd = open("./file1",O_RDWR);

        int filesize = lseek(fd,0,SEEK_END);

        printf("file size is: %d\n",filesize);

        close(fd);

        return 0;
}
file size is: 19

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值