lseek

4 篇文章 0 订阅


1. 每个打开的文件都有一个与其相关的“文件位置”。

2. 文件位置通常是一个非负整数,
unix_c_03.txt
用以度量从文件头开始计算的字节数。

3. 读写操作都从当前文件位置开始,
并根据所读写的字节数,增加文件位置。

4. 打开一个文件时,除非指定了O_APPEND,
否则文件位置一律被设为0。

5. lseek函数仅将文件位置记录在内核中,
并不引发任何I/O动作。

6. 在超越文件尾的文件位置写入数据,
将在文件中形成空洞。

7. 文件空洞不占用磁盘空间,但被算在文件大小内。
#include <sys/types.h>
#include <unistd.h>
off_t lseek (
int fd, // 文件描述符
off_t offset, // 偏移量
int whence // 起始位置
);
成功返回当前文件位置,失败返回-1。
whence取值:
SEEK_SET - 从文件头
(文件的第一个字节)。
SEEK_CUR - 从当前位置
(上一次读写的最后一个字节的下一个位置)。
SEEK_END - 从文件尾
(文件的最后一个字节的下一个位置)。
范例:seek.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int main (void) {
int fd = open ("seek.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror ("open");
return -1;
}

const char* text = "Hello, World !";
if (write (fd, text, strlen (text) * sizeof (text[0])) == -1) {
perror ("write");
return -1;
}

if (lseek (fd, -7, SEEK_CUR) == -1) {
perror ("lseek");
return -1;
}

off_t pos = lseek (fd, 0, SEEK_CUR);
if (pos == -1) {
perror ("lseek");
return -1;
}

printf ("当前文件位置:%ld\n", pos);

text = "Linux";
if (write (fd, text, strlen (text) * sizeof (text[0])) == -1) {
perror ("write");
return -1;
}

if (lseek (fd, 8, SEEK_END) == -1) {
perror ("lseek");
return -1;
}

text = "<-这里有个洞洞!";
if (write (fd, text, strlen (text) * sizeof (text[0])) == -1) {
perror ("write");
return -1;
}

off_t size = lseek (fd, 0, SEEK_END);
if (size == -1) {
perror ("lseek");
return -1;
}

printf ("文件大小:%ld字节\n", size);

close (fd);

return 0;
}
思考:既然lseek系统调用相当于标C库函数fseek,
那么是否存在与标C库函数ftell相对应的系统调用?
不存在,
因为通过lseek(fd,0,SEEK_CUR)就可以获得当前文件位置。


如何获取文件的大小?
通过lseek(fd,0,SEEK_END)可以获得文件的大小。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值