Connecting Tech Pros Worldwide Forums | Help | Site Map

easy way to modify textfile

Gunnar G
Guest
 
Posts: n/a
#1: Jul 23 '05
Hello.
If I wish to open a huge textfile and only change the 300th line in the
file, how do I do that?



Maxim Yegorushkin
Guest
 
Posts: n/a
#2: Jul 23 '05

re: easy way to modify textfile


On Wed, 06 Jul 2005 11:49:13 +0400, Gunnar G <debian@comhem.se> wrote:
[color=blue]
> If I wish to open a huge textfile and only change the 300th line in the
> file, how do I do that?[/color]

Use a stream editor, such as sed.

--
Maxim Yegorushkin
<firstname.lastname@gmail.com>
Gunnar G
Guest
 
Posts: n/a
#3: Jul 23 '05

re: easy way to modify textfile


> Use a stream editor, such as sed.
And if that is not an option?
I solved it by storing all the lines in a vector, then reopen the file in
non-appending mode and write all the lines.

There must be a better way...

Maxim Yegorushkin
Guest
 
Posts: n/a
#4: Jul 23 '05

re: easy way to modify textfile


On Wed, 06 Jul 2005 12:23:18 +0400, Gunnar G <debian@comhem.se> wrote:
[color=blue][color=green]
>> Use a stream editor, such as sed.[/color]
> And if that is not an option?
> I solved it by storing all the lines in a vector, then reopen the file in
> non-appending mode and write all the lines.
>
> There must be a better way...[/color]

You could read the file by chunks in a buffer rather then reading the
whole in the vector. This way you avoid all the problems related to memory
allocation.

--
Maxim Yegorushkin
<firstname.lastname@gmail.com>
Karl Heinz Buchegger
Guest
 
Posts: n/a
#5: Jul 23 '05

re: easy way to modify textfile


Gunnar G wrote:[color=blue]
>
> Hello.
> If I wish to open a huge textfile and only change the 300th line in the
> file, how do I do that?[/color]

open input file
open a new file for output

counter = 0;

while( line can be read from input ) {
increment counter
if counter equals 300
write replacement line to output
else
write original line to output
}

close input file
close output file
delete input file
rename output file to the input file name

done

--
Karl Heinz Buchegger
kbuchegg@gascad.at
Panjandrum
Guest
 
Posts: n/a
#6: Jul 23 '05

re: easy way to modify textfile


Gunnar G wrote:[color=blue][color=green]
> > Use a stream editor, such as sed.[/color]
> And if that is not an option?
> I solved it by storing all the lines in a vector, then reopen the file in
> non-appending mode and write all the lines.
>
> There must be a better way...[/color]

If the line isn't longer or shorter afterwards you can use random
access.

Closed Thread


Similar C / C++ bytes