在Linux C编程中,seek
函数(通常通过lseek
系统调用实现)用于改变文件描述符的当前偏移量。这个函数对于随机访问文件特别有用,因为它允许程序在文件中任意移动,而不仅仅是顺序读取或写入。
lseek
函数的原型通常如下:
off_t lseek(int fd, off_t offset, int whence);
fd
是要操作的文件描述符。offset
是要移动的字节数。whence
是移动的起始点,通常是SEEK_SET
(从文件开始处)、SEEK_CUR
(从当前位置)或SEEK_END
(从文件末尾)。lseek
函数返回一个off_t
类型的值,表示新的文件偏移量。如果出错,则返回-1,并设置errno
。
errno
以确定具体错误原因(如EBADF
表示无效的文件描述符,EINVAL
表示无效的参数等)。lseek
版本(如lseek64
),并使用适当的偏移类型(如off64_t
)。ulimit
命令或修改系统配置)。#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
off_t offset = lseek(fd, 10, SEEK_SET);
if (offset == -1) {
perror("lseek");
close(fd);
return 1;
}
char buffer[256];
ssize_t bytesRead = read(fd, buffer, sizeof(buffer) - 1);
if (bytesRead == -1) {
perror("read");
close(fd);
return 1;
}
buffer[bytesRead] = '\0';
printf("Data at offset 10: %s
", buffer);
close(fd);
return 0;
}
这个示例程序打开一个文件,将文件偏移量设置为10,然后读取并打印从该位置开始的字符串。
领取专属 10元无门槛券
手把手带您无忧上云