Chapter 7  File Operations
Is my machine a file cabinet?

Computers are an excellent means of storing information and most modern computers have a large storage space called a hard drive.  The information is stored in what is known as a file.  This file is just that; it is a place to put information, although the format and purpose of a file may vary.  Tcl/Tk is pretty friendly when working with files.  Below is an example to show some of the concepts of reading and writing information to and from files:

######################
# Simple File example
# written by Nelson
# file1.tcl
# Use a proc to get info passed from a entry
# widget and append to a file.
#
# Also have a button to get the info from the file.
######################
######################
# Proc section
######################
proc putin {fileName info} {
  set fileID [open $fileName a+]
  puts $fileID "$info"
  close $fileID
  }

proc getout {fileName} {
  set fileID [open $fileName r]
  set msg ""
  while {[gets $fileID line] >=0} {
  set msg "$msg $line"
        }
   close $fileID
   return $msg
  }
################
# Main code
################
entry .e1 -textvar sloppyJoe
button .b1 -text Input -command { putin myfile.txt $sloppyJoe
  set sloppyJoe ""
 }
button .b2 -text Output -command {
  if [winfo exists .m1] {destroy .m1}
  message .m1 -width 125m -text [getout myfile.txt]
  pack .m1
  place .m1 -x 10 -y 70
 }
####################
# pack and place
####################
pack .b1 .b2 .e1
place .e1 -x 10 -y 10
place .b1 -x 10 -y 35
place .b2 -x 80 -y 35

Screen shots before Input button is pressed and after Output button is pressed.

Assignment 7.45
Write down what you think the format of myfile.txt will be.  Open myfile.txt with a text editor to see the format of the file.  Write down any differences you find.

Assignment 7.46
Write a program that will accept input of a mailing form for a shipping service.  Place the forms information in a file called shipinfo.txt.  The file format is as follows:
(All information is on 1 line!)
LastNameFrom|FirstNameFrom|AddressFrom|CityFrom|StateFrom|ZipFrom|
LastNameTo|FirstNameTo|CareOf|AddressTo|CityTo|StateTo|ZipTo

As with any command you do not understand, you should examine the manual page for the command in question.  I think it is very important to understand there is different ways to open files.  At this time, I would strongly suggest you take a closer look at how you can access files in Tcl/Tk.

Assignment 7.47
List all ways to open files in Tcl/Tk and explain each in detail.  Modify the example file1.tcl, for each type, see what can happen in each.
 


Next Section

Table of Contents