open(3tcl)
β¨ NAME β¨
open β open a file-based or command pipeline channel
okay so hi bestie π this is the page for open(3tcl), from the Tcl Built-In Commands manual. It's a long one, so buckle up, hydrate, and let's go π«Ά
πΈ SYNOPSIS πΈ
open fileName
open fileName access
open fileName access permissions
π DESCRIPTION π
This command opens a file, a serial port, or a command pipeline, and hands you back a channel identifier that you can use in future invocations of commands like read, puts, and close. Iconic behaviour, honestly. β¨
If the first character of fileName is not |, then the command opens a file: fileName gives the name of the file to open, and it has to conform to the conventions described in the filename manual entry. No cap.
The access argument, if you bother to pass it, tells Tcl how the file (or command pipeline) is meant to be accessed. In the first form, access can be any of these:
rβ open the file for reading only; the file must already exist. This is the default value if access isn't 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. (yes it will absolutely eat your existing content, be normal about it π)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. If the file doesn't exist, create a new empty file. Set the file pointer to the end of the file prior to each write. βοΈ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.
All of the legal access values above can have the character b added as the second or third character in the value, which signals that the opened channel should be configured as if with the fconfigure -translation binary option β making the channel suitable for reading or writing of binary data. π§
In the second form, access is a list of any of the following flags, most of which have the standard POSIX meanings. One of the flags must be either RDONLY, WRONLY or RDWR. periodt.
RDONLYβ open the file for reading only.WRONLYβ open the file for writing only.RDWRβ open the file for both reading and writing.APPENDβ set the file pointer to the end of the file prior to each write.BINARYβ configure the opened channel with the-translation binaryoption.CREATβ create the file if it doesn't already exist (without this flag it is an error for the file not to exist).EXCLβ ifCREATis also specified, an error is returned if the file already exists. π«NOCTTYβ if the file is a terminal device, this flag prevents the file from becoming the controlling terminal of the process.NONBLOCKβ prevents the process from blocking while opening the file, and possibly in subsequent I/O operations. The exact behavior of this flag is system- and device-dependent; its use is discouraged (it's better to use thefconfigurecommand to put a file in nonblocking mode). For details, refer to your system documentation on theopensystem call'sO_NONBLOCKflag. π
lowkey a trap, bestie β the docs literally say discouraged. use fconfigure instead, iykyk.
TRUNCβ if the file exists it is truncated to zero length.
If a new file is created as part of opening it, permissions (an integer) is used to set the permissions for the new file in conjunction with the process's file mode creation mask. permissions defaults to 0666. π
When the file opened is an ordinary disk file, the chan configure and fconfigure commands can be used to query this additional configuration option:
-statβ this option, when read, returns a dictionary of values much as is obtained from thefile statcommand, where that stat information relates to the real opened file. Keys in the dictionary may includeatime,ctime,dev,gid,ino,mode,mtime,nlink,size,type, anduidamong others; themtime,sizeandtypefields are guaranteed to be present and meaningful on all platforms; other keys may be present too. π
Implementation note: this option maps to a call to fstat() on POSIX platforms, and to a call to GetFileInformationByHandle() on Windows; the information reported is what those system calls produce.
π₯ COMMAND PIPELINES π₯
If the first character of fileName is | then the remaining characters of fileName are treated as a list of arguments that describe a command pipeline to invoke, in the same style as the arguments for exec. Main character energy, truly. β¨
In this case, the channel identifier returned by open may be used to write to the command's input pipe or read from its output pipe, depending on the value of access.
- If write-only access is used (e.g. access is
w), then standard output for the pipeline is directed to the current standard output unless overridden by the command. - If read-only access is used (e.g. access is
r), standard input for the pipeline is taken from the current standard input unless overridden by the command.
The id of the spawned process is accessible through the pid command, using the channel id returned by open as argument. π«Ά
If the command (or one of the commands) executed in the command pipeline returns an error (according to the definition in exec), a Tcl error is generated when close is called on the channel β unless the pipeline is in non-blocking mode, then no exit status is returned (a silent close with -blocking 0). π
It is often useful to use the fileevent command with pipelines so other processing may happen at the same time as running the command in the background. multitasking queen behaviour π
π¦ SERIAL COMMUNICATIONS π¦
If fileName refers to a serial port, then the specified serial port is opened and initialized in a platform-dependent manner. Acceptable values for the fileName to use to open a serial port are described in the PORTABILITY ISSUES section.
The chan configure and fconfigure commands can be used to query and set additional configuration options specific to serial ports (where supported):
-modebaud,parity,data,stop β this option is a set of 4 comma-separated values: the baud rate, parity, number of data bits, and number of stop bits for this serial port. The baud rate is a simple integer that specifies the connection speed. Parity is one of the following letters:n,o,e,m,s; respectively signifying the parity options of "none", "odd", "even", "mark", or "space". Data is the number of data bits and should be an integer from5to8, while stop is the number of stop bits and should be the integer1or2. π-handshaketype β (Windows and Unix). This option is used to setup automatic handshake control. Note that not all handshake types maybe supported by your operating system. The type parameter is case-independent.
If type is none then any handshake is switched off. rtscts activates hardware handshake. Hardware handshake signals are described below. For software handshake xonxoff the handshake characters can be redefined with -xchar. An additional hardware handshake dtrdsr is available only under Windows. There is no default handshake configuration, the initial value depends on your operating system settings. The -handshake option cannot be queried.
-queueβ (Windows and Unix). The-queueoption can only be queried. It returns a list of two integers representing the current number of bytes in the input and output queue respectively. π-timeoutmsec β (Windows and Unix). This option is used to set the timeout for blocking read operations. It specifies the maximum interval between the reception of two bytes in milliseconds. For Unix systems the granularity is100milliseconds. The-timeoutoption does not affect write operations or nonblocking reads. This option cannot be queried.-ttycontrol{signal boolean signal boolean ...} β (Windows and Unix). This option is used to setup the handshake output lines (see below) permanently or to send a BREAK over the serial line. The signal names are case-independent.{RTS 1 DTR 0}sets the RTS output to high and the DTR output to low. The BREAK condition (see below) is enabled and disabled with{BREAK 1}and{BREAK 0}respectively.
it is not a good idea to change the RTS (or DTR) signal with active hardware handshakertscts(ordtrdsr). The result is unpredictable. π The-ttycontroloption cannot be queried.
-ttystatusβ (Windows and Unix). The-ttystatusoption can only be queried. It returns the current modem status and handshake input signals (see below). The result is a list of signal,value pairs with a fixed order, e.g.{CTS 1 DSR 0 RING 1 DCD 0}. The signal names are returned upper case. π₯-xchar{xonChar xoffChar} β (Windows and Unix). This option is used to query or change the software handshake characters. Normally the operating system default should beDC1(0x11) andDC3(0x13) representing the ASCII standard XON and XOFF characters.-closemodecloseMode β (Windows and Unix). This option is used to query or change the close mode of the serial channel, which defines how pending output in operating system buffers is handled when the channel is closed. The following values for closeMode are supported:defaultβ indicates that a system default operation should be used; all serial channels default to this.discardβ indicates that the contents of the OS buffers should be discarded.
Note that this is not recommended when writing to a POSIX terminal, as it can interact unexpectedly with handling of stderr. π
drainβ indicates that Tcl should wait when closing the channel until all output has been consumed. This may slow downclosenoticeably. π
to be continued, bestie β more parts incoming πβ¨
-inputmode inputModeβ (Unix only; Windows has the equivalent option on console channels). Bestie, this one lets you query or change the input mode of the serial channel β it's assuming the channel is talking to a terminal, which is what controls how interactive user input gets handled. Here's the whole menu ofinputModevalues you can throw at it:normalβ the chill default vibe: normal line-oriented input, with all the standard terminal editing capabilities turned on. β¨passwordβ non-echoing input. Standard terminal editing is still enabled, but nothing you type gets written back to the terminal (except newlines). Some terminals might flag this specially. π«£rawβ no filter, no processing, all keyboard input goes straight to Tcl and the terminal does literally nothing. It doesn't even echo your keys β interpreting what to do is 100% on the Tcl script. πreset(set only) β tells the terminal to go back to whatever state it was in when it was opened. It's giving "undo my whole era". π
Heads up: setting this option (technically, anything that changes the terminal state from its initial value through this option) makes the channel turn on an automatic reset of the terminal when the channel is closed. So it cleans up after itself. Iconic behaviour, ngl.
-winsizeβ (Unix only; Windows has the equivalent option on console channels). This one is query only β it just hands you back a two-element list with the current width and height of the terminal. π-pollinterval msecβ (Windows only). This sets the maximum time between polling for fileevents. It affects the time interval between checking for events across the whole Tcl interpreter (the smallest value always wins). Only reach for this if you wanna poll the serial port more or less often than10 msec, which is the default. β±οΈ-sysbuffer inSize-sysbuffer {inSize outSize}β (Windows only). This changes the size of the Windows system buffers for a serial channel. Especially at higher communication rates, the default input buffer size of4096bytes can overrun on latent systems π. First form = just the input buffer size; second form = both input and output buffers get defined. π§Ί-lasterrorβ (Windows only). Query only, bestie. If a serial communication error happens,readorputsreturns a general Tcl file I/O error. That's when you callfconfigure -lasterrorto get a list of error details. The various error codes are explained below π.
β¨ SERIAL PORT SIGNALS β¨
RS-232 is the most commonly used standard electrical interface for serial communications, no cap. A negative voltage (-3V..-12V) defines a mark (on=1) bit, and a positive voltage (+3..+12V) defines a space (off=0) bit (RS-232C). The following signals are specified for incoming and outgoing data, status lines, and handshaking. π«Ά
Here we're using the term workstation for your computer and modem for the external device, because some signal names (DCD, RI) literally come from modems. Of course your external device might be using these signal lines for something totally different β it's giving "borrowed terminology" energy. π
TXD(output) β Transmitted Data: outgoing serial data. π€RXD(input) β Received Data: incoming serial data. π₯RTS(output) β Request To Send: this hardware handshake line tells the modem that your workstation is ready to receive data. Your workstation may automatically reset this signal to indicate that the input buffer is full. π΅CTS(input) β Clear To Send: the complement toRTS. Indicates the modem is ready to receive data. βDTR(output) β Data Terminal Ready: this signal tells the modem the workstation is ready to establish a link.DTRis often enabled automatically whenever a serial port is opened. πDSR(input) β Data Set Ready: the complement toDTR. Tells the workstation the modem is ready to establish a link. π€DCD(input) β Data Carrier Detect: this line goes active when a modem detects a "Carrier" signal. π‘RI(input) β Ring Indicator: goes active when the modem detects an incoming call. βοΈBREAKβ lowkey not a hardware signal line at all! It's a logical zero on theTXDorRXDlines for a long period of time, usually250to500milliseconds. Normally a receive or transmit data signal just sits at the mark (on=1) voltage until the next character comes through. ABREAKis sometimes used to reset the communications line or switch up the operating mode of communications hardware. π
π ERROR CODES π (Windows only)
A lot of different errors can pop off during serial read operations or during event polling in the background. The external device might've been switched off, the data lines might be noisy, system buffers might overrun, or your mode settings might just be wrong. That's exactly why reliable software should always catch serial read operations. π€
When an error happens, Tcl returns a general file I/O error. Then fconfigure -lasterror can help you locate the problem. These are the error codes that may come back:
RXOVERβ Windows input buffer overrun. The data comes in faster than your script reads it, or your system is overloaded. Usefconfigure -sysbufferto avoid a temporary bottleneck and/or make your script faster. πββοΈTXFULLβ Windows output buffer overrun. The complement toRXOVER. This error should practically never happen, because Tcl actually cares about the output buffer status. π«‘OVERRUNβ UART buffer overrun (hardware) with data lost. The data comes faster than the system driver receives it. Check your advanced serial port settings to enable the FIFO (16550) buffer and/or setup a lower(1) interrupt threshold value. π³οΈRXPARITYβ a parity error has been detected by your UART. Wrong parity settings withfconfigure -modeor a noisy data line (RXD) may cause this. πFRAMEβ a stop-bit error has been detected by your UART. Wrong mode settings withfconfigure -modeor a noisy data line (RXD) may cause this one too. πΌοΈBREAKβ aBREAKcondition has been detected by your UART (see above). π
π PORTABILITY ISSUES π
Windows
Valid values for fileName to open a serial port are of the form comX, where X is a number, generally from 1 to 9. A legacy form that's also accepted is comX: β but bestie, that notation only works for serial ports 1 to 9. If you try to open a serial port that doesn't exist or has a number greater than 9, it will fail. π
An alternate form of opening serial ports is to use the filename //./comX, where X is any number that corresponds to a serial port. ποΈ
When running Tcl interactively, there may be some strange interactions between the real console (if one is present) and a command pipeline that uses standard input or output. If a command pipeline is opened for reading, some of the lines you type at the console get sent to the command pipeline and some get sent to the Tcl evaluator. π΅βπ« If a command pipeline is opened for writing, keystrokes entered into the console are not visible until the pipe is closed. These problems only happen because both Tcl and the child application are fighting over the console at the same time β it's giving "two main characters, one microphone". π€ If the command pipeline is started from a script (so Tcl isn't touching the console), or if the pipeline doesn't use standard input or output but is redirected from or to a file, then the above problems don't occur. β¨
Files opened in the "a" mode or with the APPEND flag set are implemented by seeking immediately before each write, which is not an atomic operation and does not carry the guarantee of strict appending that's present on POSIX platforms. β οΈ
Unix
Valid values for fileName to open a serial port are generally of the form /dev/ttyX, where X is a or b, but honestly the name of any pseudo-file that maps to a serial port may be used. Advanced configuration options are only supported for serial ports when Tcl is built to use the POSIX serial interface. π§
When running Tcl interactively, there may be some strange interactions between the console (if one is present) and a command pipeline that uses standard input. If a command pipeline is opened for reading, some of the lines entered at the console get sent to the command pipeline and some get sent to the Tcl evaluator. Same "competing for the console" situation as above. π If the command pipeline is started from a script (so Tcl isn't accessing the console), or if the pipeline doesn't use standard input but is redirected from a file, then the above problem doesn't occur. πΈ
See the PORTABILITY ISSUES section of the exec command for additional information β not specific to command pipelines β about executing applications on the various platforms. π
π₯οΈ CONSOLE CHANNELS π₯οΈ
okay bestie, listen β this whole section is Windows only, no cap. Console channels (which is usually just stdin or stdout) support these two extra options, and only these two:
-inputmodeinputMode β this one lets you ask about or change the input mode of the console channel, which is basically the vibe-check on how interactive typing from users gets handled. Here's what you can pass for inputMode:normalβ standard line-oriented input, with all the normal console editing stuff turned on. It's giving default behavior, it's giving nothing weird.passwordβ non-echoing input. You still get the standard console editing capabilities, but literally nothing you type gets written to the terminal (except newlines, those still show). Secretive. Mysterious. Iconic.rawβ ALL keyboard input goes straight to Tcl and the console does zero processing. It does not echo the keys at all, so it's fully on your Tcl script to figure out what to do with them. Main character energy, but the script has to carry the whole plot.reset(set only) β puts the console back to whatever state it was in when the console channel was first opened. Rewind. Undo. Slay.
heads up: setting this option β technically, anything that changes the console state away from its default via this option β makes the channel turn on an automatic reset of the console when the channel gets closed. So it cleans up after itself whether you remembered or not. π«Ά
-winsizeβ this one is query only. It hands you a two-element list with the current width and height of the console this channel is talking to. Just a lil peek at the dimensions, no writing. π
ngl there's a plot twist here: the equivalent options do exist on Unix too, but they live on the serial channel type instead. iykyk.
β¨ EXAMPLES β¨
okay these are the fun ones, let's go π
Open a file for writing, forcing it to be created and raising an error if it already exists.
set myNewFile [open filename.txt {WRONLY CREAT EXCL}]
Open a file for writing as a log file.
set myLogFile [open filename.log "a"]
fconfigure $myLogFile -buffering line
Open a command pipeline and catch any errors:
set fl [open "| ls this_file_does_not_exist"]
set data [read $fl]
if {[catch {close $fl} err]} {
puts "ls command failed: $err"
}
Open a command pipeline and read binary data from it. Note the unusual form with |[list β that handles the non-trivial edge cases where your arguments might have spaces in them. lowkey a lifesaver fr fr.
set fl [open |[list create_image_data $input] "rb"]
set binData [read $fl]
close $fl
Read a password securely from the user (this assumes the script is being run interactively, okay? don't come for me):
chan configure stdin -inputmode password
try {
chan puts -nonewline "Password: "
chan flush stdout
set thePassword [chan gets stdin]
} finally {
chan configure stdin -inputmode reset
}
see how it resets in the finally? that's the good manners. that's the etiquette. we love to see it. π
π SEE ALSO π
your reading list, bestie, go be curious:
file(3tcl)close(3tcl)filename(3tcl)fconfigure(3tcl)gets(3tcl)read(3tcl)puts(3tcl)exec(3tcl)pid(3tcl)fopen(3)
π KEYWORDS π
the search terms, the tags, the algorithm fuel β¨
access mode, append, create, file, non-blocking, open, permissions, pipeline, process, serial
and that's the whole page, babes π this one came straight out of the Tcl 8.3 manual β it's the open(3tcl) page, and yeah the version is giving vintage but the knowledge is timeless π go open some files responsibly, mwah π
π¦ where this page comes from
- ubuntu questing: tcl9.0-doc 9.0.2+dfsg-1
- ubuntu resolute: tcl9.0-doc 9.0.3+dfsg-1
- ubuntu stonking: tcl9.0-doc 9.0.4+dfsg-1
- Copyright (c) 1993 The Regents of the University of California
- Copyright (c) 1994-1996 Sun Microsystems, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms