writing in a "txt" file

hello i need some help plzz

i have a file named "names.txt" which contains the names :

"james
mike
jane
terry
jake "

and when i try to overwrite "jane" with "adam" i use "fprintf", the problem is that the program erases everything and write only "adam"

how can I keep all the names and replace only "jane" with "adam"???

if you have any hints plzz comment ... :D
When you open the file you probably used fopen( "names.txt", "w" );, right?

Make sure to open using "r+": this will give you read mode with modifications allowed.

Next, make sure to seek properly to "jane". The best way to do that is to use ftell() before each line read. Once you have read "jane", use fseek() to restore your position in the file, and fprintf "adam".

(The reason this is important is because of newline considerations between systems.)

Hope this helps.

[edit] BTW, I hope you are aware that replacing "jane" with "adam" only works because both names have the same number of letters. If they had a different number of letters, like "jane" --> "aaron", then you would have to use a different method to modify the file:

open the file in read mode
read each line into memory
close the file

modify the lines in memory

open the file in overwrite mode
write each line to file
close the file

Good luck!
Last edited on
Topic archived. No new replies allowed.