【发布时间】:2019-09-02 22:34:28
【问题描述】:
我尝试使用系统调用 lseek() 来取回文件的开头或到达文件的结尾。
我使用的确切代码是:
int location = lseek(fd, 0, SEEK_SET) //get back to the beginning
int location = lseek(fd, 0, SEEK_END) //reach to the end
但是,在文件位置被重置后,每当我尝试使用 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;
}
【问题讨论】:
-
请给出一个完整的可编译示例,这两行代码无法解释问题
-
也许你也应该检查
lseek的返回值 -
@Fred 可重现的示例必须有一个
main函数并且没有语法错误。这意味着一个完整的程序。 -
lseek() 的返回值似乎不错。它应该是新的文件位置。
标签: c system-calls lseek