Frodo
Frodo

Reputation: 46

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?

Upvotes: 1

Views: 3863

Answers (1)

nandal
nandal

Reputation: 2634

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;
}

Upvotes: 1

Related Questions