Code Comments
Programming Forum and web based access to our favorite programming groups.Hi, I would like to know if one can do in-place file editing in Tcl. Example: I have record such as 0078 100,99,10,11,11,0,0 to be replaced by 0078 100,99,10,11,11,7,9 Can one replace this record in this file without creating a new file ? Thanks in advance, Anand
Post Follow-up to this messageAndy wrote: > > Hi, > > I would like to know if one can do in-place file editing in Tcl. > Example: > I have record such as > 0078 100,99,10,11,11,0,0 > > to be replaced by > 0078 100,99,10,11,11,7,9 > > Can one replace this record in this file without creating a new > file ? > > Thanks in advance, > Anand Yes, you can. See the script below: set outfile [open "updfile.txt" "w"] puts $outfile "First write some text ...." close $outfile set inout [open "updfile.txt" "r+"] puts $inout "xxxxx" close $inout Note: - "r+" will do the trick - puts will add an extra newline, unless you use the -nonewline option - you can not _insert_ characters Regards, Arjen
Post Follow-up to this messageAndy <kaleanand@gmail.com> wrote: : I would like to know if one can do in-place file editing in Tcl. : Example: : I have record such as : 0078 100,99,10,11,11,0,0 : to be replaced by : 0078 100,99,10,11,11,7,9 : Can one replace this record in this file without creating a new : file ? You can do it same way as text editors do: load entire file into memory, modify there and save back. It is quite easy in Tcl set f [open filename] set content [read $f] # insert code to modify content variable here set f [open filename w] puts -nonewline $content close $f. There is also possiblity to do random access to the file using scommand. But it is scarcely applicable to your case, because it would quite hard work if line length changes during editing. --
Post Follow-up to this messageHi, Thanks guys for the tips .. I use the tclX package, I can do something like this set line [bsearch $key $fp] # Modify the record returned by this puts -nonewline $fp $line # Assuming the file is opened in overwrite mode. Any comments
Post Follow-up to this messageAndy schrieb: > Hi, > > Thanks guys for the tips .. > > I use the tclX package, I can do something like this > > set line [bsearch $key $fp] > # Modify the record returned by this > puts -nonewline $fp $line # Assuming the file is opened in overwrite > mode. > > Any comments > The only way it is doable is for fixed size records. If you have those, open the file with open, search the record to modify (or calculate its position from your information about the format), use sto get there, write your fixed sized record over the one in question and close the file again. But if you need this kind of functionality it is usually a better idea to use a real database like Metakit or SQLite for storing the data. Michael
Post Follow-up to this messagePowered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.