溫馨提示×

c語言lseek函數(shù)如何使用

小億
136
2023-08-24 20:05:29
欄目: 編程語言

在C語言中,lseek函數(shù)是用于設(shè)置文件指針位置的函數(shù)。其原型如下:

#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);

參數(shù)說明:

  • fd:文件描述符,用于標(biāo)識要操作的文件。

  • offset:偏移量,可以是正數(shù)、負(fù)數(shù)或零。

  • whence:參考位置,可以是以下值之一:

  • SEEK_SET:從文件起始位置開始計算偏移量。

  • SEEK_CUR:從當(dāng)前位置開始計算偏移量。

  • SEEK_END:從文件末尾位置開始計算偏移量。

返回值:返回當(dāng)前文件指針的位置,失敗時返回-1。

使用示例:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("test.txt", O_RDWR); // 打開文件
if (fd == -1) {
perror("open");
return 1;
}
off_t pos = lseek(fd, 0, SEEK_SET); // 設(shè)置文件指針位置為文件起始位置
if (pos == -1) {
perror("lseek");
return 1;
}
char buf[100];
ssize_t n = read(fd, buf, sizeof(buf)); // 讀取文件內(nèi)容
if (n == -1) {
perror("read");
return 1;
}
printf("Read: %s\n", buf);
close(fd); // 關(guān)閉文件
return 0;
}

上述示例中,首先使用open函數(shù)打開文件,并將返回的文件描述符保存到fd變量中。然后,使用lseek函數(shù)將文件指針位置設(shè)置為文件的起始位置。接著,使用read函數(shù)讀取文件內(nèi)容,并將讀取的內(nèi)容打印出來。最后,使用close函數(shù)關(guān)閉文件。

0