tags:

views:

289

answers:

3

I am using fprintf command for writing on the text file, but every time when the function called its remove the previous data, I actually want to update the file so that the previous data remain. Kindly guide me how I can make it possible?

+1  A: 

Open the file in append mode instead:

f = fopen("logfile.txt", "a");
Peter
+3  A: 

when you open the file use "a" for append.

FILE * file = fopen("filename", "a");

http://www.cplusplus.com/reference/clibrary/cstdio/fopen/

John Knoeller
Thanks John...!
Arman
+1  A: 

There is no way to insert data "in the middle" of an existing file (nor at the start): data can be appended (put after what used to be the end of the file) or it can overwrite existing data. This is not an issue with C nor with C++ in particular: it's language-independent and connected only to how computer filesystems work.

To "make believe" you're inserting data in the middle, you have to make a new file, copy all the data that goes "before" your new data from the old file to the new one, then add your new data, and finally copy all the data that goes "after" your new data. Note that this way you're always writing to the end of the new file, i.e, appending.

When that's done, you can close the new file, remove the old one, and rename the new one to the name that the old one used to have ("rename replacing" can be an atomic operation in some cases, depending on your OS and filesystem, and if that's feasible this would be better).

Alex Martelli