Search code examples
cfopenfwritefseek

Overwrite contents of the file in C


I try to overwrite contents of the file using fwrite(), fseek() in C, but it doesn't work.

The file size is 30. I want to write "ABCD" by overwrite position 10 ~ 13 in the file. So I program below.

FILE *fp = fopen("file.txt", "a+");
fseek(fp, 10, SEEK_SET); 
fwrite("ABCD", 1, 4, fp);

But "ABCD" is written after position 30 in the file. I found some advice to use the binary mode (like "ab+") but the 'b' is ignored on all POSIX conforming systems.

How can I do this?


Solution

  • Use "r+" mode to open the file instead of "a+" (the b for binary is optional and essentially irrelevant on POSIX systems):-

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(void){
        FILE *fp = fopen("file.txt", "r+");
        fseek(fp, 10, SEEK_SET);
        fwrite("ABCD", 1, 4, fp);
        fclose(fp);
    
        return 0;
    }