Tcl : read a file

From MyWiki
Revision as of 16:07, 23 May 2014 by George2 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

http://wiki.tcl.tk/367
One way to get file data in Tcl is to 'slurp' up the file into a text variable. This works really well if the files are known to be small.

    #  Slurp up the data file
    set fp [open "somefile" r]
    set file_data [read $fp]
    close $fp

Now you can split file_data into lines, and process it to your heart's content. NOTE: The mention of split is important here- input data is seldom well-behaved/structured, and needs to be processed in this way to ensure that any potential Tcl metacharacters are appropriately quoted into list format.

    #  Process data file
    set data [split $file_data "\n"]
    foreach line $data {
         # do some line processing here
    }