Writing / appending to a specific line in text file

Hi,

With the help of some cplusplus.com users, I was able to work out how to read a specific line of text within a text file and display this in a richTextBox. See:
http://www.cplusplus.com/forum/windows/140812/

The next bit of code I'm trying to work on is to write / append to a specific line of text.

For example: Text.txt has the following lines...

001 This is line 1
002 This is line 2
003 This is line 3

Note: the numbers (e.g. 001) act like a line ID tag type of thing...

Lets say I have a form with a richTextBox and a button. I would like to have whatever is written in this richTextBox to be appended to a line ID. For example, if the text "This line has been changed" was typed into richTextBox1 clicking the button would append this to line ID 002. Once clicked, the text file would be:

001 This is line 1
002 This line has been changed
003 This is line 3

Any adice would be great, or even a link to something useful....I've spent some time googling but can't seem to find something that helps.

Cheers.
A text file has sequential access, so you'd have to rewrite the file if you wanted to insert something.
Thanks, kbw.

I thought that this would be the case... So what would be the best approach?

How about: reading entire file with say 'StreamReader' and storing it as a string, then using a 'while' loop to search for the required line ID, then overwrite that line?

I'm not exactly sure how to approach this. Obviously 'getline' wouldn't be used as this is only for reading files....

Cheers,
Last edited on
If it's small enough, read the whole thing into memory, make your changes, then write out the whole thing.
Hi kbw,

I would assume that this would be via an array? That is, each line is put into an element (is that the right term?) of an array. Then I would change that particular element, then dump everything back into that file (i.e. overwrite it)?

As for file size, I'm not too sure how big this will be but I'm guessing that it would be no more than a 1000 lines of text. Each line would vary with number of characters....

Cheers,
An array is ok, and your method is ok. The memory should be fine.

check out SetFilePointer() API.
you can point to a particular offset in the file, and edit its contents..
Topic archived. No new replies allowed.