File IO in TCL

There are basically three modes of handling files. Read, Write and Append.

Below are the ways:

#1. r -> Read a file, file must exist.
#2. w -> Write a file, If file exists, then file will get truncated.
#3. a -> Append the file, file must exist.

#4. r+ -> Open a file for read and write both, File must exist.
#5. w+-> Open a file for read and write both, If file exists, then it will truncate the file with zero length or if file doesn’t exist then it creates one.
#6. a+ -> Open a file for reading and writing both, if file doesn’t exist, then it creates one. If reading then it start from beginning and writing starts with appending.

Reading a file

Syntax: [open <file_name> r]

set file_name file1.tcl
set read_file_name [open $file_name r]
set file_details [read $read_file_name]
puts $file_details
close $file_name

Writing a file

Syntax: [open <file_name> w]

set file_name file1.tcl
set write_file_name [open $file_name w]
puts $write_file_name “This will be written in file1”
close $write_file_name

Once we are done with writing or reading a file, we need to close the file.

Admin
Admin

Leave a Reply