How to Read/Write a File with Tcl

Advertisement

Advertisement

Tcl provides an easy way to open and read the lines of a file. Check out these code snippets that demonstrate how to read and write files with Tcl programming language.

Reading a File

# $file will contain the file pointer to test.txt (file must exist)
set file [open test.txt]

# $input will contain the contents of the file
set input [read $file]

# $lines will be an array containing each line of test.txt
set lines [split $input "\n"]

# Loop through each line
foreach line $lines {
    # Do something with line here
    puts $line
}

# Clean up
close $file

Writing a File

# Open test2.txt for writing
set outputFile [open test2.txt w]

# Put some text in to the file
puts $outputFile "Goodbye, World!"

# Close the file
close $outputFile

Advertisement

Advertisement