Search code examples
cfilefseek

Fseek rolls back 8 byte,but I want it to be 4 bytes


for (int i = 0; i < num - 1 - ct; i++) {
    int tmp = k;
    fread(&k, sizeof(int), 1, fp);
    fflush(stdin);
    fseek(fp, -(sizeof(int)), SEEK_CUR);
    fwrite(&tmp, sizeof(int), 1, fp);
}

The question part is above. I want fseek to roll back 4 bytes every time. But it rolls back 8 bytes or maybe roll back to the beginning of the file. I can't make it work right. A freshman. Thanks in advance.


Solution

  • The problem is you do not use fseek() to sync the stream's internal data when switching from writing to reading from the same stream.

    Try this:

    fseek(fp, 0, SEEK_CUR);
    for (int i = 0; i < num - 1 - ct; i++) {
        int tmp = k;
        fread(&k, sizeof(int), 1, fp);
        //fflush(stdin);  // this has undefined behavior
        fseek(fp, -(sizeof(int)), SEEK_CUR);
        fwrite(&tmp, sizeof(int), 1, fp);
        fseek(fp, 0, SEEK_CUR);
    }