0

How can I insert characters in a file using C instead of overwriting? I also want to write in start of file and end of a file. I tried this method but it didn't work out (I can re-position but I cannot insert. The text is overwritten)

I've tried this, but it didn't work:

fword = fopen("wrote.txt", "rb+");
fseek(fword, 0, SEEK_SET);
fscanf(fword, "%c", &l);
1
  • 2
    There is no way to insert text into a file afaik. You can overwrite existing text or append at the end of the file. To insert things, read the file to memory, do your alterations there and then write everything back. Commented Apr 16, 2016 at 13:49

2 Answers 2

0

To add text at the end, you can open the file with "a" mode (check the fopen manual). It will write your text to end.

To add text in other positions, you have to read everything after that to memory, write what you want and then write the rest.

Sign up to request clarification or add additional context in comments.

Comments

0

Files are abstractions of byte streams, there is no such concept as insert in a byte stream, you can seek into certain place and write data there. The bytes you wrote will lay in the file as an array of bytes, if the writing exceeds the current file size, the file will be extended.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.