For Programmers: Free Programming Magazines  


Home > Archive > Tcl > April 2007 > Read/Write File in place









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Read/Write File in place
g4173c@motorola.com

2007-04-23, 7:08 pm

Hi:

I have a file:

LINE 1
LINE 2
LINE 3

I have the following code:

set inout [open "foo" "r+"]
set cnt 1
while {[gets $inout line] != -1} {
set line [string map {LINE FOO} $line]
puts $inout "$cnt $line"
incr cnt
}
close $inout

What I want to do is replace the LINE with FOO and get:

1 FOO 1
2 FOO 2
3 FOO 3

Instead I get:

LINE 1
LINE 2
LINE 3
1 FOO 1
2 FOO 2
3 FOO 3

What am I doing wrong? I thought that the each line would be operated
on and replaced...

Thanks for any help in advance.
Tom

Bruce Hartweg

2007-04-23, 7:08 pm

g4173c@motorola.com wrote:
> Hi:
>
> I have a file:
>
> LINE 1
> LINE 2
> LINE 3
>
> I have the following code:
>
> set inout [open "foo" "r+"]
> set cnt 1
> while {[gets $inout line] != -1} {
> set line [string map {LINE FOO} $line]
> puts $inout "$cnt $line"
> incr cnt
> }
> close $inout
>
> What I want to do is replace the LINE with FOO and get:
>
> 1 FOO 1
> 2 FOO 2
> 3 FOO 3
>
> Instead I get:
>
> LINE 1
> LINE 2
> LINE 3
> 1 FOO 1
> 2 FOO 2
> 3 FOO 3
>
> What am I doing wrong? I thought that the each line would be operated
> on and replaced...
>

Nope, that's not how file systems work, to overwrite a specific spot
you need to s to that spot, and then it is byte for byte replacement
meaning, so if the next stuff isn;t the exact same thing as the old you
will get weird stuff. (these are NOT record based files)

If you file is small, read it into memory, modify
it at will, then write it back out over the old file all at once. If you
are dealing with large files and don;t want the memory footprint, then
open orig for reading, write line by line mods to a temp file, and when
finished move temp file onto original file.

Bruce
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com