Previous
Procedures 
Next
TK 
Tcl/Tk Tutorial - Create GUI using Tk with Tcl Language
File Handling in Tcl/Tk

File Handling

As in all other good languages, Tcl also can open, read and write to files. And like all other good tutorials, this tutorial also teaches how to do it. First let us see how to open a file.

open

Syntax:
open fileName ?access? ?permissions?

fileName is the name of the file. The access argument, if present, specifies the way in which the file should be accessed. It can have any of the following values:

rOpen the file for reading only; the file must already exist. This is the default value if access is not specified.
r+Open the file for both reading and writing; the file must already exist.
wOpen the file for writing only. If there is a file by that name, then delete all the contents of the file. If it doesn't exist, create a new file.
w+Open the file for reading and writing. If there is a file by that name, then delete all the contents of the file. If it doesn't exist, create a new file.
aOpen the file for writing only. If the file doesn't exist, create a new empty file. Set the initial access position to the end of the file.
a+Open the file for reading and writing. If the file doesn't exist, create a new empty file. Set the initial access position to the end of the file.
Lets see an example.

#Open the file called "jokes.txt" for writing
open "jokes.txt" w

Now we know how to open a file. Not much good, is it? To make this function useful, we need to write to the file.

puts

Syntax:
puts ?-nonewline? ?channelId? string

Use the -nonewline option only if you don't need a new line at the end of the string you write to a file. The channelID stands for the ID of the output stream that must be written to(if you don't understand what the means, don't worry. You will get it latter.) string is the string you want to write to the file. Lets see the example.


#Open the file called "jokes.txt" for writing
set out [open "jokes.txt" w]
puts $out "Computers make very fast, very accurate mistakes."

Notice that I created a variable called 'out'. That will store the ID of the opened file. Always open a file in this way - otherwise they won't be of much use. Then we use that ID to write to the file using the command 'puts'. Now the file called "jokes.txt" has one line. Next we have to close the file.

close

Syntax:
close ?channelId?

This command closes the channel. Always do this - else you will cry later. Lets move on to the ever growing example...


#Open the file called "jokes.txt" for writing
set out [open "jokes.txt" w]
puts $out "Computers make very fast, very accurate mistakes."
close $out

After we close the file, we decide that we have to put more lines in the file. So now we open the file again, this time in the append mode. The example grows even longer...


#Open the file called "jokes.txt" for writing
set out [open "jokes.txt" w]
puts $out "Computers make very fast, very accurate mistakes."
close $out
set out [open "jokes.txt" a]
puts $out "Computers are not intelligent. They only think they are."
puts $out "My software never has bugs. It just develops random features."
puts $out {All computers wait at the same speed.
Best file compression around:  "DEL *.*" = 100% compression
DEFINITION: Computer - A device designed to speed and automate errors.
DEFINITION: Upgrade - Take old bugs out, put new ones in.}
close $out

After we have done that, we need to read the jokes and put them back on the screen. So we learn a new command. Ladies and Gentlemen let me introduce you to...

gets

Syntax:
gets channelId ?varName?

gets will copy one line from the channel(or file) and put it in varName. If varName is not specified, the copied line will be the result of the function. We go back to our example and get the first line of the file. For that we open the file again, this time in read mode.


#Open the file called "jokes.txt" for writing
set out [open "jokes.txt" w]
puts $out "Computers make very fast, very accurate mistakes."
close $out
#Now append more jokes at the end of the file
set out [open "jokes.txt" a]
puts $out "Computers are not intelligent. They only think they are."
puts $out "My software never has bugs. It just develops random features."
puts $out {All computers wait at the same speed.
Best file compression around:  "DEL *.*" = 100% compression
DEFINITION: Computer - A device designed to speed and automate errors.
DEFINITION: Upgrade - Take old bugs out, put new ones in.}
close $out
#Opening file in read mode
set in [open "jokes.txt" r]
gets $in line
label .line -text "First Line : $line"
pack .line

This command can be used to read the whole file line by line. See the example below to see how. Don't worry about .txt insert end "$line\n---\n" - I will explain it later.


text .txt
set in [open "Jokes.txt" r]
while {[gets $in line] != -1} {
    #Do whatever you want with the $line variable
    .txt insert end "$line\n---\n"
}
close $in
pack .txt -expand 1 -fill both

This command is for reading the file line by line. Now we decide that we need to see the entire file. For that we need the read command. But remember that if we have read one line before, the read command will read only from the second line. For resetting the channel to the first position, we need the seek command.

seek

Syntax:
seek channelId offset ?origin?

The offset and origin arguments specify the position at which the next read or write will occur for channelId. Offset must be an integer (which may be negative) and origin must be one of the following - start, current or end.

Now we have to read the file contents. So we move on to...

read

Syntax:
read channelId ?numChars?

read will take numChars characters from the channel and return it. If numChars is not specified, the whole file is read and its content will be returned. You can read a file and then get all the lines into a list with every line as an item in the list. This can be done by...


set in [open "file.txt" r]
set contents [read $in]
close $in
set lines [split $contents "\n"]

Now every item in the list called $lines is a line of the file called "file.txt". On to the example - for the last time.


#Open the file called "jokes.txt" for writing
set out [open "jokes.txt" w]
puts $out "Computers make very fast, very accurate mistakes."
close $out
#Now append more jokes at the end of the file
set out [open "jokes.txt" a]
puts $out "Computers are not intelligent. They only think they are."
puts $out "My software never has bugs. It just develops random features."
puts $out {All computers wait at the same speed.
Best file compression around:  "DEL *.*" = 100% compression
DEFINITION: Computer - A device designed to speed and automate errors.
DEFINITION: Upgrade - Take old bugs out, put new ones in.}
close $out
#Opening file in read mode
set in [open "jokes.txt" r]
gets $in line
label .line -text "First Line : $line"
pack .line
seek $in 0 start 
set contents [read $in]
close $in
label .full -text "Full file Contents... \n$contents"
pack .full

There. That's about it with file handling. Now lets move on to juicier topics.

Previous
Procedures 
Next
TK 

Comments

Anonymous at 05 Feb, 2007 01:33
hello,
i need a information, how can we interface the scprit with the devices like routers and swiches.
if you come to know about this get ae a mail. if you have a sample scprit send to me.

Regards
narasimha
Reply to this.
Binny V A at 05 Feb, 2007 05:41
I think you can do this with sockets. Tcl supports sockets - you can get more details on this subject here...
Socket
socket - Open a TCP network connection

I have not used sockets in Tcl yet - so I don't know much about this topic.
Reply to this.
Anonymous at 05 Feb, 2007 05:54

Hi all,

How to open a socket with a server [our application] running on remote
Windows machine? I need to communicate with that server by opening a
socket. I need your help. Its very urgent.

Thanks & Regards,
Narasimha.V
Reply to this.
raghu at 12 Apr, 2007 08:05
Hi all,

How can i open a tcl file and copy a variable from that file and add to a new variable in the current file??

suppose
file "xyz.tcl" contains

set x 24


and when i open the file xyz.tcl in some file can the $x be used to update some other value??
Reply to this.
Binny V A at 12 Apr, 2007 08:52
How about reading the file and then using 'eval' function to execute the statements that you want. Or, if you want to execute the entire file, use the 'source' function. Hope this helps.
Reply to this.
Ankur at 13 Apr, 2007 11:28
Yes , you can use that.

You need to include xyz.tcl in other file where you want to use it.
[ Syntax : source xyz.tcl]

Hope this helps.
Reply to this.
venu kosuri at 20 Aug, 2007 10:47
How to use ssh to login to a remote machine in TCL script and input commands to the remote machine
Reply to this.
Mahesh V. Shet at 11 Sep, 2007 06:01
Hi,

Its easy to open a socket in tcl using a tcl socket command. The syntax is as follows.

set sock [socket $hostname $portname ?myaddr? ?myport?]

The arguments within a question mark are optional. Now puts and gets on $sock will write to socket and read from socket.

Second point, if you want to ssh to a remote a host better option is to use Expect package of TCL. Its a tool for interactive applications.
Reply to this.
Anonymous at 17 Sep, 2007 07:24
HI,
Just want to know in TCL/TK how to get data from text window and dump in to one file.
Reply to this.
Anonymous at 30 Jan, 2008 02:47
Hi All,

I have one problem, i have tried out all the options but of useless. i want my script to ask for input and curser to stay at same line when i execute gets command. what are the way to do this?
Eg:
Enter your number : _
Reply to this.
Anonymous at 12 Feb, 2008 03:56
Just a typo, Change Jokes.txt to jokes.txt in example above

text .txt
set in [open "Jokes.txt" r]
...

Reply to this.
Anonymous at 03 Apr, 2008 08:21
Hi,

I could send data to serial port (e.g. com1).

-open com1 w+
-fconfigure {channelId} -mode 9600,n,8,1
-puts {channelId} 0123

But it is ASCII (0=x30, 1=x31, 2=x32, 3=x33).

How can I send binary data to serial port?

Thanks,
Reply to this.
Comment


Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed