首页 > 解决方案 > Write data after fseek(), ftell() output is wrong, the data written before fseek() are all 0

问题描述

I first write 88, then use fseek() to position the file pointer to the beginning, and write 99, then position the file pointer to the end, use ftell() to view the size of the file (the target is sizeof(int) + sizeof(int) = 8), but got 4. Finally, I tried to print out the two values I wrote (the target is 98, 88), but 99, 0 was output.

#include <stdio.h>

int main() {
    FILE* fp = fopen("a", "wb");
    int a = 88;
    fwrite(&a, sizeof(int), 1, fp);
    fseek(fp, 0, SEEK_SET);

    int c = 98;
    fwrite(&c, sizeof(int), 1, fp);

    fseek(fp, 0, SEEK_END);
    printf("%d\n", ftell(fp));

    FILE* fpc = fopen("a", "rb");
    int b;
    fread(&b, sizeof(int), 1, fpc);
    int d;
    fread(&d, sizeof(int), 1, fpc);
    printf("%d, %d\n", b, d); // 98, 0
}

gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)

标签: cfreadfseek

解决方案


推荐阅读