cprintfnewlinefseek

Cannot replace \n by using fseek and fprintf in C


I tried to reposition the cursor to \n and replace it with 3, but it turned that 3 was inserted in front of \n. Then I tried fseek (fp, 2, SEEK_SET), 3 went to the beginning of next line and 2 follows. \n still existed. Can someone explain why? Or is it just because of my compiler's problem? Thank you!

#include <stdio.h>
#include <stdlib.h>
int main (void)
{
    FILE * fp = fopen ("test2.txt", "w+");
    fprintf (fp, "1\n");
    fprintf (fp, "2\n");
    fseek (fp, 0, SEEK_SET);
    fseek (fp, 1, SEEK_SET); // or fseek (fp, 2, SEEK_SET);
    fprintf (fp, "3");
    fseek (fp, 0, SEEK_SET);
    fclose (fp);
    return 0;
}

Solution

  • You are apparently on Windows, where writing LF results in a writing a CR and a LF.

    File before seek:

    31 0D 0A 32 0D 0A
    

    As it appears on a terminal:

    1
    2
    

    File after fseek(fp, 2, SEEK_SET) and print:

    31 0D 33 32 0D 0A
    

    As it appears on a terminal:

    32
    

    Best to use ftell to get the position to which to seek.

    If this is a binary file rather than a text file, make sure to open the file as binary (using the b modifier`).