Tcl Tips -- File Processing

Most programs need to do at least a little of this!

Saving and loading TCL array variables

It's quite common to have a lot of information stored in TCL array variables, and I tend to try and keep as much as possible in arrays (as opposed to little individual variables). This makes it easier to pass the array name as an argument, etc. You can save the data in a flat text file, and parse it in line by line, but this is a waste of time. Instead, make use of the inherent power of tcl to source files.

To begin, lets say we have a bunch of data in an array variable "MyVar" which is visible in the current scope. We'll start by saving this data into a file called MyVar.dat. The trick to to write this data into the file in a format the source can read and parse.

set f [ open MyVar.dat w ]
puts $f "array set MyVar [ list [ array get MyVar ] ]"
close $f

Try this! Look at the file that's created, and verify that it looks the same as if you had typed the code in yourself (except that it will all be on one line, which Tcl doesn't mind at all.

Now, to load this back in, we just say

source MyVar.dat

Since MyVar.dat is in tcl source format, we can just read it in like regular commands.

Parsing a file

Say you have a procedure that you use to parse strings, and you want to apply this procedure to all the data in a file. Here's a simple scrap that can do this (The parsing procedure is called "ParseLine" in this case).

set f [ open $filename ] 
while { [ gets $f line ] != -1 } {
    ParseLine $line
}

This will parse one line at a time. If you want to parse the whole file in one go, try this.

set f [ open $filename ] 
while { [ gets $f line ] != -1 } {
    append all_lines $line
}
ParseLine $all_lines

You can do this a little simpler using read.

set f [ open $filename ]
set all_lines [ read $f ]

This reads the file until the end of the line. If you are reading a binary file, you'll want to set binary translation on input (and output if you have any) using the tcl command fconfigure



This document last modified: Friday, November 05, 2004 me@rustybrooks.com