简体   繁体   English

为什么fseek从不返回-1

[英]why fseek never return -1

I am using ubuntu 14.04 and try to read binary file, but fseek never return -1 for out of file size. 我正在使用ubuntu 14.04并尝试读取二进制文件,但是fseek从不为文件大小返回-1。

Why this happend? 为什么会这样?

#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;
    }
}

Short reason: seeking to a position that exceeds the file size is not regarded as an error in fseek . 简短原因:寻求超过文件大小的位置在fseek不视为错误。

The following sections are quoted from man 3 fseek : 以下部分引自man 3 fseek

RETURN VALUE 返回值

The rewind() function returns no value. rewind()函数不返回任何值。 Upon successful completion, fgetpos() , fseek() , fsetpos() return 0 , and ftell() returns the current offset. 成功完成后, fgetpos()fseek()fsetpos()返回0 ,而ftell()返回当前偏移量。 Otherwise, -1 is returned and errno is set to indicate the error. 否则,返回-1并将errno设置为指示错误。

ERRORS 错误

EBADF The stream specified is not a seekable stream. EBADF指定的流不是可搜索的流。
EINVAL The whence argument to fseek() was not SEEK_SET , SEEK_END , or SEEK_CUR . EINVAL whence参数到fseek()没有被SEEK_SETSEEK_END ,或SEEK_CUR Or: the resulting file offset would be negative. 或:结果文件偏移量将为负。

Which means: 意思是:

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM