0

How to edit a file programmatically in linux? It seems a very basic question. I am surprised to see that currently i see no way to do this.

I have a file with me. I wish to edit it.

From man pages, I thought "a+" mode will enable me to edit the file, but it seems that we can only append it in the end of the file, and not use it if we wish to make changes in the initial portions of the file.

I wish to update some information, say a name in the header a custom object i created, how can I do it programmatically?

I tried:

FILE *fp = fopen(path, "a+");
fseek(fp, DESIRED_OFFSET, SEEK_SET);
fwrite("KOLAVERIDI", 10, 1, fp);
fclose(fp);

I thought, fseek would do the job. But, like man pages say

a+ Open for reading and appending (writing at end of file).

it is always appending at the end of the file(though I seek to a different offset before fwrite()).

So my question basically is how can i Edit/Update a file in C?

Sandeep
  • 18,356
  • 16
  • 68
  • 108
  • possible duplicate of [C write in the middle of a binary file without overwriting any existing content](http://stackoverflow.com/questions/10467711/c-write-in-the-middle-of-a-binary-file-without-overwriting-any-existing-content) – Theolodis May 26 '14 at 06:40
  • you need to check if `fopen` fails. if it does it will return `NULL`. – H_squared May 26 '14 at 06:40

2 Answers2

7

If you want to be able to write in the middle of a file, you need to open the file in "extended" read mode, with "r+".

Do note that then writing in the middle of the file will overwrite the contents at that position. It will not insert the data you write.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

You have to open the file that you need with

fopen(path, "r+");

This way you open it to write and read.

Teo Zec
  • 383
  • 2
  • 11