fseek 不适用于空文件

fseek does not work with empty file

我有以下代码:

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

当我用一个空的二进制文件调用它时,没有发生错误,尽管我希望 fseek() 到 return 和 -1。有谁知道为什么这没有发生?

没错。 fseek 寻找过去的文件结尾时不要失败。

来自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.