Sunday, July 26, 2009

How do i add data to different sections of a text file with c++?

I want be able to add data to a text file and then go to different parts of the file based on where a certain word is that marks the begining of a section of data.


for example:


(this is the text file)


INPUT


a


b


c


d


e


(^this section is where one type of data, here input data, is stored)


OUTPUT


z


y


x


w


v


(^here another type of data would be kept in this case the output data)


and so on with different key words (INPUT, OUTPUT, MISC...etc) marking the beginning of each section.


i want to be able to add data to one section then to a different section to either read or write data and then go back to another section. hope this makes enough sense. if you need more information tell me and ill add it. thanks

How do i add data to different sections of a text file with c++?
This is a reasonably hard problem, although there are several possible answers. The key is that without using some exotic technique you will have to open a new file for writing, write the old and new content to it, and then close the new file. Then you can remove or rename the old file and rename the new file.





One idea would be to read the file totally into memory structures and then manipulate them. Finally you'd write the end result file. If you really must do it "randomly" you'll have to read the file and write it to the new file as you go. Then you can decide where to insert new things (or delete things, whatever). Then do the rename. So in psudeo code:





Open "f1" for reading


Open "f1.new" for writing


Read first section tag. If it isn't INPUT, just copy each subsequent line to the new file until you find the INPUT tag.


Read lines and write them out until you find the next section tag (don't write the section tag)


Write new "INPUT" values out to the new file


Now write the next section tag and continuing copying the whole file.


Close the new file (be sure to check for errors)


Close f1


Rename f1 to f1.bak


Rename f1.new to f1





Proceed....

verbena

No comments:

Post a Comment