Procedures
TK
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:
| r | Open 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. |
| w | Open 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. |
| a | Open 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. |
#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.

Comments
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
Socket
socket - Open a TCP network connection
I have not used sockets in Tcl yet - so I don't know much about this topic.
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
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??
You need to include xyz.tcl in other file where you want to use it.
[ Syntax : source xyz.tcl]
Hope this helps.
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.
Just want to know in TCL/TK how to get data from text window and dump in to one file.
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 : _
text .txt
set in [open "Jokes.txt" r]
...
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,
how can i read data from a file which is continouslly getting data from another exec command...
i.e i am executing one c program which is writing some data into the file and at the same time i need the data written to file on my text area...how to do that..
Actually one f my text file is growing because of one c file open command ..
now i need to read the contents of the same file at that instant only and redirect the output to text area...i am getting line by line output on console window...but in text area once the command gets executed then only its showing the output...
can u help me in it
for example
open "|./log"
this file is giving input to abc.txt
now what i need is to get the ouptut on text area
rather than on console
i am using .textarea insert end $line
but once all the lines gets buffered and file stops to grow then only its displaying the output
help me out
Below is my code..
I am executing ping 10.100.12.20 >>ping_log.txt
proc createLog {} {
global base
set naptime 10
set fd [open ping_log.txt r]
while {[gets $fd out] >= 0} {
$::status configure -state normal #my Scrolled text window..
$::status insert end "$out\n" #text window.
after $naptime
}
catch {close $fd}
$::status configure -state disabled
}
First, you have to configure open channel to be binary (so TCL wont do any translation there):
# ...
set chan [open file.txt r]
fconfigure $chan -encoding binary
# ...
When you communicate with such channel, be aware. If you will to use internal tcl commands (string etc.), use "binary scan" after reading channel or "binary format" before writing to channel, to convert between byte-string and tcl's unicode representation.
It is wise to read the whole 'binary' documentation page and links from there.
how do i link an executable C file with the button ????? Plz help..
thanks,
file, line by line, i dont know it does not work, why?
thanks
but i have another problem, how can i compare two files?
How to open multiple files at the same time in tcl script ?
set f1 [open "file1.txt" "r"]
set f2 [open "file2.txt" "r"]
set f3 [open "file3.txt" "w"]
# ...
# some code, which reads files f1 and f2 and writes to f3
# ...
close $f1
close $f2
close $f3
can u please tell me which command is used to see the history of a file and file system.
Regards,
Preethi.
I am no tcl expert but hoping that there is someone out there.
How do I write a script that change content in a xml file and then save it to a new file?
I want to change <Port>80</Port ranging from 80 to 89 and creating 10 new files with this changes
thx,
Michael
In this file, I have various segments begining with *xx, wherr xx can be anything. Always * plus 2 characters. I need to start
new line when any 3 characters = *xx.
How do I accomplish that?
I do not want to re-write the file.
Input file is stored locally.
<input_file> <output_file>
where input_file : netlist file
output_file : output where net names will be stored
I have a file haveing the contents in the following format.
12 12354.21 4253.154
14 12.12 4578
2 12 45.36 etc.....
I want to do the manupulation of each colums (by adding all the contents columnwise, here 3 columns are there.)
I want to know how can i read the fine...can give me any logic for this.?
How to insert a line in the text file (beginning, after the 4th line, etc.) in tcl? Thanks.
Can any one tell me how to create one new file while executing the tcl file.
I have a .tcl file with some data. few data i need to write in .txt file and save it.
please help how to do this.....
a, strong, em, b, i, code, pre, pandbrallowed. Other tags will be shown as code(< will become <). Urls, Line breaks will be auto-formated.