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)可以获得文件的大小。
lseek
最新推荐文章于 2023-02-17 12:47:04 发布