c – Writing to a file before already written text

Question:

So, there is text, for example: "I am in school", which is written to a file in the program. It is necessary to write the additional word "good" before the word school (in the same program). If I try to do this with fprinf , the word school is simply overwritten. How to do this without overwriting the words, but shifting them to the right?

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
FILE *fp;

if ((fp = fopen ("skul.txt", "w")) == NULL) {
    printf ("ERROR of open file skul.txt\n");
    exit (EXIT_FAILURE);
}

fprintf (fp, "i lern in skul");


if (fclose (fp) != 0) {
    printf ("ERROR of exit from file skul.txt\n");
    exit (EXIT_FAILURE);
}

if ((fp = fopen ("skul.txt", "r+")) == NULL) {
    printf ("ERROR of open file skul.txt\n");
    exit (EXIT_FAILURE);
}

fseek (fp, 10L, SEEK_SET);

fprintf (fp, "good ");

if (fclose (fp) != 0) {
    printf ("ERROR of exit from file skul.txt\n");
    exit (EXIT_FAILURE);
}

return EXIT_SUCCESS;
}

Answer:

There are 2 options, you can try changing w to w + when writing, it will give you the opportunity to complete the file. 2nd option: read the sentence to the desired character, then count from this character to the end, get 2 char arrays, then add your word and overwrite it in the file, a little more difficult but it will definitely work.

Scroll to Top