text file editing

  • Thread starter Thread starter Jon
  • Start date Start date
J

Jon

I am trying to accomplish the following with a text file...

1 open the file
2 loop through it line by line
3 if need be, modify the current line
4 replace the old line in the file with the newly modified line
5 close the file

I know how to do 1,2,3 and 5, but I'm not having any luck writing the
modified line back to the file (preferably at the same position) and
removing the old line.

Can anyone shed some light on that portion of it? Thanks
 
Jon said:
I am trying to accomplish the following with a text file...

1 open the file
2 loop through it line by line
3 if need be, modify the current line
4 replace the old line in the file with the newly modified line 5
close the file

I know how to do 1,2,3 and 5, but I'm not having any luck writing
the modified line back to the file (preferably at the same position)
and removing the old line.

Can anyone shed some light on that portion of it? Thanks


You can not modify a line unless it's length didn't change.

If the length has changed, read the rest of the file after the line to be
modified, set the Position property of the stream, write the new line and
write the rest of the file.

If the length did not change, set the Position property and write the new
line.


Take into account that, depending on the encoding of the file, the resulting
number of bytes in the file might change although the number of chars did
not change.

Armin
 
Jon said:
I am trying to accomplish the following with a text file...

1 open the file
2 loop through it line by line
3 if need be, modify the current line
4 replace the old line in the file with the newly modified line
5 close the file

I know how to do 1,2,3 and 5, but I'm not having any luck writing the
modified line back to the file (preferably at the same position) and
removing the old line.

Can anyone shed some light on that portion of it? Thanks
One approach that comes to mind is to create a second file and write the
lines to it, replacing each edited line with the modified data. Once through
all lines in the original file, the second file would contain all the lines
from the original, but with modified lines in place.
 

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

Back
Top