easy way to modify textfile

G

Gunnar G

Hello.
If I wish to open a huge textfile and only change the 300th line in the
file, how do I do that?
 
G

Gunnar G

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...
 
M

Maxim Yegorushkin

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...

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.
 
K

Karl Heinz Buchegger

Gunnar said:
Hello.
If I wish to open a huge textfile and only change the 300th line in the
file, how do I do that?

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
 
P

Panjandrum

Gunnar said:
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...

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top