linux下lseek函數(shù)怎么使用

小億
102
2023-08-24 19:54:34

lseek函數(shù)用于設(shè)置文件指針的偏移量。

其函數(shù)原型為:

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

參數(shù)說明:

  • fd:文件描述符

  • offset:偏移量

  • whence:偏移的起始位置,有以下三個(gè)值:

  • SEEK_SET:文件起始位置

  • SEEK_CUR:當(dāng)前位置

  • SEEK_END:文件末尾位置

函數(shù)返回值為新的文件指針位置,若執(zhí)行失敗則返回-1,并設(shè)置errno。

示例代碼:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("test.txt", O_RDWR); // 打開文件
if (fd == -1) {
perror("open");
exit(1);
}
off_t offset = lseek(fd, 0, SEEK_END); // 將文件指針定位到文件末尾
if (offset == -1) {
perror("lseek");
exit(1);
}
printf("File size: %ld\n", offset);
close(fd); // 關(guān)閉文件
return 0;
}

該示例代碼打開一個(gè)文件,將文件指針定位到文件末尾,并打印文件大小。

0