• Advertisement
Sign in to follow this  

appending specific lines using fstream.h

This topic is 4216 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Are there any ways at all of doing this?
Its going to be impossible for me to re write the entire file.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Quote:
Original post by Fixxer
Its going to be impossible for me to re write the entire file.


Why do you think this is?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement