linux

Linux中的lseek函数怎么使用

小亿
86
2023-12-16 21:05:59
栏目: 智能运维

在Linux中,lseek函数用于设置文件偏移量。它的原型如下:

#include <unistd.h>

off_t lseek(int fd, off_t offset, int whence);

参数说明:

返回值:

下面是一个使用lseek函数的示例:

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>

int main() {
    int fd = open("test.txt", O_RDWR);
    if (fd == -1) {
        perror("open");
        return 1;
    }

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

    printf("Current offset: %ld\n", offset);

    close(fd);
    return 0;
}

这个示例中,首先通过open函数打开一个文件,然后使用lseek函数将文件偏移量设置为文件末尾位置(0表示偏移量为0)。最后,打印出新的文件偏移量。

注意,使用lseek函数时需要注意文件打开方式。如果文件以只读方式打开(例如使用O_RDONLY标志),则lseek函数将不起作用。

0
看了该问题的人还看了