我正在使用 ubuntu 14.04 并尝试读取二进制文件,但 fseek 永远不会因文件大小不足而返回 -1。
为什么会发生这种情况?
#include <stdio.h>
int main() {
const char *fn = "myfile";
FILE * fid;
fid = fopen(fn, "r");
int flag;
while(1) {
flag = fseek(fid, sizeof(float), SEEK_CUR);
printf("flag: %d\n",flag);
if(flag)
break;
}
}
最佳答案
简短原因:在 fseek
中,查找超出文件大小的位置不会被视为错误。
以下部分引用自man 3 fseek
:
RETURN VALUE
The
rewind()
function returns no value. Upon successful completion,fgetpos()
,fseek()
,fsetpos()
return0
, andftell()
returns the current offset. Otherwise,-1
is returned and errno is set to indicate the error.ERRORS
EBADF
The stream specified is not a seekable stream.
EINVAL
The whence argument tofseek()
was notSEEK_SET
,SEEK_END
, orSEEK_CUR
. Or: the resulting file offset would be negative.
这意味着:
// This is not an error
int ret_0 = fseek(file, 1, SEEK_END);
assert(ret_0 == 0);
// While this is an error
int ret_1 = fseek(file, -1, SEEK_SET);
assert(ret_1 == -1);
关于c - 为什么 fseek 永远不会返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25833104/