gpt4 book ai didi

c - 为什么fseek从不返回-1

转载 作者:太空狗 更新时间:2023-10-29 12:03:28 25 4
gpt4 key购买 nike

我正在使用 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() return 0, and ftell() 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 to fseek() was not SEEK_SET, SEEK_END, or SEEK_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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com