File handling

Now that we can open, read, write, and close a file, it is time to put this knowledge to work in a real world manner. We will now create a Tcl script that accesses a file, reorders the stored data, and then outputs it to a secondary file. This is similar to a file handling procedure used to clean up user supplied files.

Getting ready

Using the text editor of your choice create a text file containing the following text:

	1,3,5,7,8,2,4,6,9

Save the file in your working directory as input.txt.

How to do it…

Using the text editor of your choice create the following Tcl script and save it in your working directory as filehandler.tcl.

# Check that a filename was provided
if { $argc>0 & $argv>0} {
 # Assign the filename to a variable
 set fname [lindex $argv 0]
 # Open the file for read-only access
 set fp [open $fname r]
 # Read the contents of the file into a variable
 set data [read $fp]
 #Close the input file
 close $fp
 # Split the data and create a Tcl list
 set input [split $data ","]
 # Sort the list and load it into another list
 set output [lsort -increasing $input]
 # Open a file to write the data to
 set fp [open output.txt w]
 # Read through the list and write the data
 foreach item $output {
  puts $fp $item
 }
 #Close the file
 close $fp
 } else {
  puts "No filename provided... Exiting Script"
  exit
}

Launch your Tcl shell appropriately, based on your operating platform. Enter the following command line:


% tclsh filehandler.tcl input.txt
%

How it works…

By combining the capabilities of the Tcl, file handling commands with the Tcl list functionality we are able to read in a comma delimited list of data and output it to a file sorted and line-by-line. To confirm the output, use the text editor of your choice and view the file output.txt. It should contain a sorted listing of the integers provided, one per line, as shown next:


1
2
3
4
5
6
7
8
9
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.216.175