Working With Files

Tcl has commands for accessing files. The open command opens a file. The second argument determines how the file should be opened. "r" opens a file for reading; "w" truncates a file and opens it for writing; "a" opens a file for appending (writing without truncation). The second argument defaults to "r“.

open "/etc/passwd" "r"
open "/tmp/stuff.[pid]" "w"

The first command opens /etc/password for reading. The second command opens a file in /tmp for writing. The process id is used to construct the file name—this is an ideal way to construct unique temporary names.

The open command returns a file identifier. This identifier can be passed to the many other file commands, such as the close command. The close command closes a file that is open. The close command takes one argument—a file identifier. Here is an example:

set input [open "/etc/passwd" "r"]    ;# open file
close $input                          ;# close same file

The open command is a good example of a command that is frequently evaluated from a catch command. Attempting to open (for reading) a nonexistent file generates an error. Here is one way to catch it:

if [catch {open $filename} input] {
    puts "$input"
    return
}

By printing the error message from open, this fragment accurately reports any problems related to opening the file. For example, the file might exist yet not allow permission to read it.

The open command may also be used to read from or write to pipelines specified as /bin/sh-like commands. A pipe character (”|“) signifies ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.