Click to See Complete Forum and Search --> : inserting text to file
mikledet
February 21st, 2003, 02:38 PM
Hi All,
Sorry if this is already answered - but my searches on codeguru are timing out if it has more then one word in the search -today:rolleyes:
I am trying to insert text to an open input text file.
I have no problem writing to the file - but I want to INSERT text somewhere in the middle - not just append to the end.
Is there a function that does that - or do i have to manully take care of it i.e :
1. get to the insersion position
2. cpy the rest of the file to a buffer
3. write the text i want to add to the file
4. append the "rest" buffer
I would preffer to use a "ready made" function if there is one.
Thanks in advance
Dani.
gangaprasad
February 21st, 2003, 02:50 PM
Use fseek(filePointer, numberOfBytesFromOrigin, origin)
where origin having value of SEEK_CUR or SEEK_END or SEEK_SET
Refer documentation for full details.
mikledet
February 21st, 2003, 03:09 PM
gangaprasad,
I am using seekg and seekp - to find my way in the file - this is not my problem.
May be i was not clear -
My problem is to insert - in oposite of override - text in a position in the text which is not the end of file - which means - to add string that will move the rest of the text "foeward" in the file - and not add the text "on" the exsiting one...
Seek will only help me move the pointer in the file - but not deal with the "overriden" text...
All the best
Dani
stober
February 21st, 2003, 06:53 PM
it is not possible to just insert the text. You must rewrite at least part of the file. two ways I can think of:
1. rewrite the entire file. This could be time consuming if its a big file.
2. Read the file into memory starting from where you want to insert the new string. Write the new string to the file, then rewrite the rest of the file.
mikledet
February 21st, 2003, 07:12 PM
stober,
Yes, this is what i did.
I was hoping there was a ready made function for that...
Thanks.
stober
February 21st, 2003, 07:15 PM
Nope. I don't know of any other way to do it.
doumalc++
February 21st, 2003, 09:38 PM
Naah!
There has to be a way to insert text into a file.
stober
February 22nd, 2003, 08:35 AM
well, if you discover it I'm sure you could make a ton of money on the copyright.
JamesSchumacher
February 24th, 2003, 11:08 PM
Is to load the file into memory and insert the text that way. Most people would just use std::string - easiest way, then write back to the file.
-OR-
You could open a temporary empty file, read up to the part you want to insert in, write that in the temp, write your inserted text, read the rest of the source text file - write that in the temp, close the source and temp, delete the source, and move/rename the temporary to the original source filename.
Once again - elementary.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.