固定(见最终编辑)
我正在尝试使用 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) 并且它不起作用,尽管它仍然返回 42。
编辑 2:删除了幻数。
最终编辑:通过添加 #include <unistd.h> 修复