File Operation Examples in Tcl
Let's explore file operations in Tcl by creating a chipworld.txt
file and placing it in the bin directory.
The input file |
The Input File
Reading the Entire File at Once
Example (1):
Example 1:
set fp [open "chipworld.txt" r]
set content [read $fp]
puts $content
close $fp
Output:
chip world is the best vlsi blog
Reading File Line by Line
Example (1): read the following file
The input file |
tclset file [open "chipworld.txt" r] while {[gets $file data] >= 0} { puts $data } close $file
Output:
chip world is the best vlsi blog
learn TCL with us
Writing File Contents
Example (1): Note that this code will remove all file content and write the required content.
set file [open "chipworld.txt" w]
puts $file "TCL (Tool Command Language)"
close $files
The output file
The output file |
Nested List and File Operation
We consider a file with multiple lines as a nested list.
Example (1): We want to write multiple lines to a file.
set file [open "chipworld.txt" w]
puts $file "chip world is the best vlsi blog"
puts $file "learn TCL with us"
puts $file "please, follow us"
puts $file "please, visit us"
close $file
To read the last elements of each line:
tclset file [open "chipworld.txt" r] while {[gets $file line] >= 0} { puts "[lindex $line end]" } close $file
Output:
blog us us us
Arrays in Tcl
Array Syntax
tclset zoo(animal1) donkey set zoo(animal2) caw set zoo(animal3) lion puts $zoo(animal1) ;# Output: donkey puts $zoo(animal2) ;# Output: caw puts $zoo(animal3) ;# Output: lion
Array Commands
Array Size:
tclarray size zoo ;# Output: 3
Array Names:
array names zoo ;# Output: animal2 animal3 animal1
Array Stack:
array get zoo ;# Output: animal2 caw animal3 lion animal1 donkey
Using Arrays in Foreach Loop
Example 1:
foreach name_array [array names zoo] {
puts "$name_array $zoo($name_array)"
}
Output:
animal2 caw animal3 lion animal1 donkey
Example 2:
foreach {zoo_array zoo_name} [array get zoo] {
puts "$zoo_array $zoo_name"
}
Output:
animal2 caw animal3 lion animal1 donkey
Test for Understanding
Question 1: Write to a file line by line and get the last element of the file.
Solution:
Write to chipworld.txt
file:
set file [open "chipworld.txt" w]
puts $file "chip world is the best vlsi blog"
puts $file "learn TCL with us"
puts $file "please, follow us"
puts $file "please, visit us"
close $file
the output file |
Reading the last word in the file:
set file [open "chipworld.txt" r]
set last_element {}
while {[gets $file line] >= 0} {
set last_element [lindex $line end]
}
puts "Last element of the file: $last_element"
close $file
Output:
us
0 Comments