appending specific lines using fstream.h

Started by
3 comments, last by Zahlman 17 years, 8 months ago
How can I change certain lines of a file using the fstream functions? Or is there a different header that makes this easier? I have a file is alsmot 2,500 lines but I only need my program to change a few specific lines when I ask it to.
Advertisement
Nitpick: fstream.h is prestandard. #include<fstream> instead.

Your thread title mentions appending. This can be done simply by opening the file in append mode (or moving the write cursor to the end of the file with seekp) and writing.

As for changing lines: no. Files are stored sequentially in memory. Consider the following text:

Hello
World

This is stored on disk as Hello\nWorld (with the \n being \r or \r\n on different systems). Now, notice that the character in 7th psition is a W. If you replace the first line by a shorter text, like Bye:

Bye
World

Then the file representation is Bye\nWorld, with the 7th character being r. As a consequence, every time you change a line, all the text after that line must be moved around to take into account the change of length of the given line. What you can do is read a vector of lines, change one of these, and write it back.

In any situation, a large portion of the file will have to be rewritten anyway.

EDIT: a common method is to use a diff file, which only includes the number of the modified lines, and their new value. You can save all your modifications to this file, and whenever necessary you can rewrite the original file by applying the modification in the diff file. This allows you to save time by not rewriting the file every single time.

You can also decide to use a database, which can store lines as entries in a table.
Are there any ways at all of doing this?
Its going to be impossible for me to re write the entire file.
Well, as I said above, you can use a database, or a diff file. You can also create a special binary file format which implements text as linked lists: use blobs of given size, one per line, with lines too long to fit in a single blob continued on blobs at the end of the file. Move around blobs when one of them is deleted to make more space.
Quote:Original post by Fixxer
Its going to be impossible for me to re write the entire file.


Why do you think this is?

This topic is closed to new replies.

Advertisement