lseek SEEK_END 没有得到最后一个字符

lseek SEEK_END doesn't get last character

已修复(查看最终编辑)

我正在尝试使用 lseek 获取文件的最后一个字符并读取。我打开的文件是这个(末尾没有'\n'):

the quick brown fox jumps over the lazy dog

我希望输出为 'd'。出于某种原因,执行 lseek(file, -1, SEEK_END) 似乎不起作用。但是,在它工作后添加一个冗余的 lseek(file, position, SEEK_SET) 。我的代码:

int file;
char c;
int position;

/*************** Attempt 1 (does not work) ***************/

file = open("test", O_RDONLY);
position = lseek(file, -1, SEEK_END);
printf("lseek returns %i\n", position);
printf("read returns %i\n", read(file, &c, 1));
printf("last character is \"%c\"\n\n", c);
close(file);

/********* Attempt 2 (seems redundant but works) *********/

file = open("test", O_RDONLY);
position = lseek(file, -1, SEEK_END);
printf("lseek returns %i\n", position);

/* ADDED LINES */
position = lseek(file, position, SEEK_SET);
printf("lseek returns %i\n", position);

printf("read returns %i\n", read(file, &c, 1));
printf("last character is \"%c\"\n\n", c);
close(file);

给出输出:

lseek returns 42
read returns 0
last character is ""

lseek returns 42
lseek returns 42
read returns 1
last character is "g"

有谁知道发生了什么事吗?


编辑:我试过用 lseek(file, 0, SEEK_CUR) 代替 lseek(file, position, 0) 但它不起作用,尽管它仍然是 returns 42。

编辑 2:删除了幻数。


最终编辑:通过添加#include

修复

通过添加

解决了问题
#include <unistd.h>