使用 lseek() 系统调用重置文件位置

Fre*_*red 2 c system-calls lseek

我尝试使用系统调用 lseek() 来返回文件的开头或到达文件的结尾。

我使用的确切代码是:

int location = lseek(fd, 0, SEEK_SET) //get back to the beginning
int location = lseek(fd, 0, SEEK_END) //reach to the end
Run Code Online (Sandbox Code Playgroud)

但是,在重置文件位置后,每当我尝试使用 read() 时,read() 的返回值总是设置为 -1,这意味着出现了问题。此外,我收到的 errno 消息是错误的文件描述符。有谁知道我应该做什么?

PS:我尝试关闭并重新打开文件以帮助我回到文件的开头,并且它有效。但我不知道如何在不使用 lseek() 的情况下到达文件末尾并以相反的顺序读取整个文件。

另外:一个可重现的例子是:

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

int main(void)
{
    int fd;
    char buffer[1000];

    fd = creat("newFile", 0777);

    memset(buffer, 'a', 500);
    write(fd, buffer, 500); // fill up

    int location = lseek(fd, 0, SEEK_SET); //get back to the beginning

    int read_bytes = read(fd, buffer, 500);
    // this should return the bytes it reads but it actually returns -1
    printf("%d\n", read_bytes);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

JL2*_*210 5

creat函数不允许您读取文件。它只允许您写入。

creat(2)

creat()
调用 tocreat()相当于调用open()equal flagsto O_CREAT|O_WRONLY|O_TRUNC

这里重要的部分是O_WRONLY。这意味着“只写”。

如果您想打开文件(并创建它)以进行读写,那么您可以open像这样使用:

int fd = open("newFile", O_CREAT|O_RDWR|O_TRUNC, 0777);
Run Code Online (Sandbox Code Playgroud)

这里重要的部分是O_RDWR。这意味着“读和写”。
如果您想open在文件已存在时给出错误,请添加O_EXCL标志;当您尝试创建文件时,这会导致-1返回并errno设置为EEXIST文件是否已存在。