0

I have the following code:

int main(int argc,char *argv[]){

    FILE *fp;

    if(argc != 2){
        perror("Please specify a file");
        return 1;
    }

    if((fp=fopen(argv[1], "rb")) == 0){
        perror("File not found!");
        return 2;
    }

    int a = fseek(fp, 1000, SEEK_CUR);

    if(a<0){
        printf("fail\n");
    }

    fclose(fp);

    return 0;
}

When I call this with an empty binary file, no error occurs, eve though I would expect fseek() to return with -1. Does anyone know why is this not happening?

tomooka
  • 1,091
  • 2
  • 9
  • 12
  • Yes, thats the case. Thanks! – tomooka Feb 08 '15 at 20:02
  • 1
    This is by design. If you invoke an `fwrite(string, 1, strlen(string), fp)` call after the `fseek` call in your program, the file will get padded with 1000 null chars before the string. – selbie Feb 08 '15 at 20:02

2 Answers2

1

From the documentation of fseek

POSIX allows seeking beyond the existing end of file. If an output is performed after this seek, any read from the gap will return zero bytes. Where supported by the filesystem, this creates a sparse file.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
0

That is correct. fseek do not fail when you seek past end-of-file.

StenSoft
  • 9,369
  • 25
  • 30