Monday, 12 December 2016

TCL File Handling with Examples

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:

File modes:

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. Truncate it if it exists. If it doesn't exist, create a new file.
w+ == Open the file for reading and writing. Truncate it if it exists.
            If it doesn't exist, create a new file.

a  ==   Open the file for writing only. The file must already exist, and the file is positioned
            so that new data is appended to 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.


In TCl , by default stdout is output channel id.

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?
close $out

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.
-------------------------
How do I read and write files in Tcl
One way to get file data in Tcl is to 'slurp' up the file into a text variable. This works really well if the files are known to be small.
     #  Slurp up the data file
     set fp [open "somefile.txt" r]
     set file_data [read $fp]
     close $fp
Now you can split file_data into lines, and process it to your heart's content. NOTE: The mention of split is important here- input data is seldom well-behaved/structured, and needs to be processed in this way to ensure that any potential Tcl metacharacters are appropriately quoted into list format.
     #  Process data file
     set data [split $file_data "\n"]
     foreach line $data {
          # do some line processing here
     }


 #  read the file one line at a time
     set fp [open "somefile.txt" r]
     while { [gets $fp data] >= 0 } {
          puts $data
     }
     close $fp

#Writing a file
# create some data
        set data "This is some test data.\n"
        # pick a filename - if you don't include a path,
        #  it will be saved in the current directory
         set filename "test.txt"
        # open the filename for writing
         set fileId [open $filename "w"]
        # send the data to the file -
        #  failure to add '-nonewline' will result in an extra newline
        # at the end of the file
        puts -nonewline $fileId $data
        # close the file, ensuring the data is written out before you continue
        #  with processing.
        close $fileId


 Find duplicate files from different directories.

set searcrhResults {dir1/dir2/dir3/file1.tcl   dir1/dir3/file1.tcl   dir1/dir2/file1.tcl   dir1/dir2/dir3/file2.tcl   dir1/dir2/dir3/file3.tcl   dir1/dir3/file2.tcl   dir1/file3.tcl   dir1/file4.tcl }

foreach file $searcrhResults {
  if {[catch {incr filenames([file tail $file],cnt)}]} {
      set filenames([file tail $file],cnt) 1
  }
      lappend filenames([file tail $file],paths) [file dirname $file]
}


#append
#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

Read :
 set fp [open "somefile.txt" r]
 set file_data [read $fp]
 close $fp

 set fp [open "somefile.txt" r+]
 set file_data [read $fp]
 set data "hello how r u"
 puts  $fp $data
 close $fp
 Now if u open a file ..vi somefile.txt ..hello how r u --will be added

Write:
# create some data
set data "This is some test data.\n"
# pick a filename - if you don't include a path,it will be saved in the current directory
set filename "test.txt"
# open the filename for writing
set fileId [open $filename "w"]
# send the data to the file - failure to add '-nonewline' will result in an extra newline
# at the end of the file
puts -nonewline $fileId $data
# close the file, ensuring the data is written out before you continue with processing.
close $fileId

#FILE CONCEPTS & explain me regsub with example.
set fW [open write w]
puts $fW "MY FIRST LINE"
puts $fW "My Second Line"
close $fW
set fR [open write r]
set content [read $fR]
puts $content
#now
regsub -nocase -all "my" $content "Our" content
puts $content
close $fR
OUTPUT:
 MY FIRST LINE
My Second Line
Our FIRST LINE
Our Second Line

##File operations print the contents of a file and next make multiple lines of a file to single line in that file
set fp [open shiva w]
puts $fp "Hi My name is shiva"
puts $fp "I am workig in wipro"

close $fp
set fp [open shiva r]
set contents [read $fp]
close $fp
set contents [split $contents "\n"]
set fp [open shiva w]
foreach line $contents {
append new $line
}
puts $fp $new
close $fp
set fp [open shiva r]
set cnt [read $fp]
puts $cnt
OUPUT:
Hi My name is shiva
I am workig in wipro

Hi My name is shivaI am workig in wipro

No comments:

Post a Comment

Note: only a member of this blog may post a comment.