neouyghur
neouyghur

Reputation: 1647

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.

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

Upvotes: 2

Views: 1382

Answers (1)

starrify
starrify

Reputation: 14781

Short reason: seeking to a position that exceeds the file size is not regarded as an error in fseek.

The following sections are quoted from 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.

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

Upvotes: 3

Related Questions