| 2.3 Copying a File Line by Line |
|
|
Here, in pseudocode form, is the loop which copies a file line by line from input to output. while another line is read into Line from input file write Line to output file endwhile Procedures for reading and writing lines are required for implementing this
pseudocode. These procedures are named To read a line from a file, use gets, whose first argument is an open-file identifier and whose second argument is the name of the variable to receive the line. If the file identifier is contained in the variable InFile and if the input line is to be placed in the variable Line, then this is the way gets is invoked: gets $InFile LineNote that the value of InFile and the name of Line are passed to gets.
The result of executing gets this way is that the next input line of the file referenced by InFile is read to the variable named Line and the number of characters in that line is returned. Any characters which mark the end of the input line are removed and not included in the count of characters. If the end of the file prevents any characters from being read, the value -1 is returned. To write a line to a file, use puts, whose first argument is an open-file identifier and whose second argument is the string that is to be written. If the file identifer is the value of the variable OutFile and if the string to be written is in the variable Line, then this is the way puts is invoked: puts $OutFile $LineThe result of executing this procedure is that the value of the variable Line is written to the file referenced by OutFile and then the output line is terminated. When variables are passed to procedures, their names or their values can be passed. Passing the value of a variable X to a procedure is as easy as writing $X in the argument's position. Variable substitution will arrange for the correct value to be substituted before the argument is passed to the procedure. Passing the name is even easier, just write X in the argument's position. No variable substitution is involved. Because the purpose of gets' second argument is to name a variable whose value is to be changed, this argument should be a variable name, not a variable value. Remark
Both gets and puts have single argument forms:
Whichever form you use, puts will write an entire output line, that is, it will append an end-of-line character (or characters) to your string. If you do not want puts to do this, then place the switch -nonewline puts before any argument. For example,
puts -nonewline {Hellow Orld}
will write "Hellow Orld" to standard output without finishing
the output line.
|
Author's Home Page |
|
Order from Amazon. |