rize
rize

Reputation: 859

C++ write to a specific part of text file without overwriting

I'm writing a simple calendar application which saves the data in a text file. I use the iCalendar-format, so my text file ends "END:VCALENDAR".

When the user adds a new event, the application should write the associated data at the end of the text file without overwriting "END:VCALENDAR", how can I do this? What about deleting an event which is saved in the middle of the text file? Is there a need to write the whole file again using the updated data? Many thanks.

Upvotes: 0

Views: 1717

Answers (3)

James Kanze
James Kanze

Reputation: 153899

There isn't any way of inserting into the middle of a file; the underlying OS doesn't support it. The usual technique is to copy the file into a temporary file, making whatever modifications you need to along the line, then (and only if there are no errors on the output of the copy—do verify that the output stream has not failed after the close) delete the input file and rename/move the temporary file to the original name.

Upvotes: 2

Nikhil Girraj
Nikhil Girraj

Reputation: 1143

There is no method supported by the C++ libraries that, unlike append, gives an option to insert at any specific position into a file; be it a text or a binary file.

There are two options for you then: First is the one you are presuming, that is, read the whole file, update the data and write it back again. Second is to seek in the file to the last line's first character E as in END:VCALENDAR, write your event and then append "END:VCALENDAR" to it.

And yes, you can find that first character of last line, E right after the last newline character, programmatically. Sorry, there isn't really any other way around, as far as I know.

Upvotes: 1

DarkWanderer
DarkWanderer

Reputation: 8866

You can't dynamically "expand" the file by writing in the middle of it. You'll need to, either:

  1. Deserialize the whole calendar to memory, then write it back (best option)
  2. Read into memory everything which lies past the point you want to insert the data, write you data, then write the stored file "tail"

Upvotes: 2

Related Questions