Showing posts with label tcl. Show all posts
Showing posts with label tcl. Show all posts

Reading from a file in tcl

It is very common to read from and/or write to a file in any programming language. In tcl also, one frequently uses file operations. read command in tcl reads the entire file and stores it into a variable. One can, then, perform the desired operations onto the read data. The normal command sequence to read a file in tcl language is as below:

// script to read and display contents
set infile [open input_file.rpt r] // Create a file pointer and point it to the file to be read
set file_data [read $infile]            // Assign file_data with contents of infile
close $infile                                        // Detach the file pointer from file to be read
set lines [split $file_data “\n”]   
// Split the file contents by lines and assign each line to an element of list
foreach element $lines {
                puts $element                  // Display each element of $lines onto screen.
}