open(n)
โจ NAME โจ
okay so this is open(n) from the Tcl Built-In Commands, bestie. it's giving "open a file-based or command pipeline channel" and it's literally the main character of file I/O. ๐
open โ Open a file-based or command pipeline channel.
๐ฆ SYNOPSIS ๐ฆ
open fileName
open fileName access
open fileName access permissions
๐ DESCRIPTION ๐
okay so open opens a file, a serial port, or a command pipeline and returns a channel identifier that may be used in future invocations of commands like read, puts, and close. 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 must conform to the conventions described in the filename manual entry. no cap. ๐
The access argument, if present, indicates the way in which the file (or command pipeline) is to be accessed. In the first form access may have any of the following values:
rโ Open the file for reading only; the file must already exist. This is the default value ifaccessis 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 does not exist, create a new file. โ๏ธw+โ Open the file for reading and writing. Truncate it if it exists. If it does not exist, create a new file. ๐ฅaโ Open the file for writing only. If the file does not 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 does not exist, create a new empty file. Set the initial access position to the end of the file. ๐
All of the legal access values above may have the character b added as the second or third character in the value to indicate 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. periodt. ๐งฌ
In the second form, access consists of 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.
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 does not 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 is better to use thefconfigurecommand to put a file in nonblocking mode). For details refer to your system documentation on theopensystem call'sO_NONBLOCKflag. ๐ฉ
bestie, fr fr:NONBLOCKis discouraged. the exact behavior is system- and device-dependent, and it's better to usefconfigureto put a file in nonblocking mode. don't say I didn't warn you. ๐ญ
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 tofstat()on POSIX platforms, and to a call toGetFileInformationByHandle()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. 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. iykyk. ๐
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). not me getting a Tcl error at close time ๐
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. ๐ง
๐ธ 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):
-mode baud,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. ๐-handshake typeโ (Windows and Unix). This option is used to setup automatic handshake control. Note that not all handshake types maybe supported by your operating system. Thetypeparameter is case-independent. Iftypeisnonethen any handshake is switched off.rtsctsactivates hardware handshake. Hardware handshake signals are described below. For software handshakexonxoffthe handshake characters can be redefined with-xchar. An additional hardware handshakedtrdsris available only under Windows. There is no default handshake configuration, the initial value depends on your operating system settings. The-handshakeoption 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. ๐ฅ๐ค-timeout msecโ (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 is 100 milliseconds. 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. โ ๏ธ
bestie, seriously: changing RTS (or DTR) while active hardware handshakertscts(ordtrdsr) is on? the result is unpredictable. don't do it. ๐
-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. ๐ค-closemode closeModeโ (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 forcloseModeare 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 ofstderr. ๐๏ธdrainโ indicates that Tcl should wait when closing the channel until all output has been consumed. This may slow downclosenoticeably. ๐ฐ
-inputmode inputModeโ Unix only, bestie (Windows has the equivalent option on console channels, iykyk). This one is for peeking at or changing the input mode of a serial channel โ and it assumes the thing on the other end is talking to a terminal, which is what controls how interactive input from users gets handled. Here's the vibe check on the values you can pass for inputMode:normalโ normal line-oriented input, standard terminal editing capabilities enabled. Chill, classic, no notes. โจpasswordโ non-echoing input, standard terminal editing capabilities enabled BUT nothing you type gets written to the terminal (newlines excepted). Some terminals may indicate this specially. It's giving secretive ๐rawโ all keyboard input goes straight to Tcl with the terminal doing literally zero processing. It does not echo the keys โ interpreting what to do with them is entirely the Tcl script's problem. Main character energy, no training wheels.reset(set only) โ resets the terminal to whatever state it was in when the terminal was opened. Undo button, basically. ๐
Heads up: setting this option โ technically, anything that changes the terminal state from its initial value via this option โ will cause the channel to turn on an automatic reset of the terminal when the channel is closed. It's a whole thing. It's handled. Don't stress. ๐ซถ
-winsizeโ Unix only (again, Windows has the equivalent option on console channels). This one is query only, no setting, no touching. It retrieves a two-element list with the the current width and height of the terminal. Cute, right? ๐ฆ-pollinterval msecโ Windows only. Sets the maximum time between polling for fileevents. This affects the time interval between checking for events throughout the Tcl interpreter (and the smallest value always wins, every time, no cap). Only reach for this option if you want to poll the serial port more or less often than10 msecโ which is the default, btw. โฐ-sysbuffer inSize-sysbuffer {inSize outSize}โ Windows only. Changes the size of Windows system buffers for a serial channel. Especially at higher communication rates the default input buffer size of4096bytes can overrun for latent systems ๐ญ. First form = input buffer size only. Second form = both input and output buffers get defined. Pick your fighter.-lasterrorโ Windows only, query only. In case of a serial communication error,readorputsreturns a general Tcl file I/O error.fconfigure -lasterrorcan be called to get a list of error details. See below for an explanation of the various error codes. Detective mode activated ๐
โก SERIAL PORT SIGNALS โก
RS-232 is the most commonly used standard electrical interface for serial communications. A negative voltage (-3V..-12V) define a mark (on=1) bit and a positive voltage (+3..+12V) define a space (off=0) bit (RS-232C). The following signals are specified for incoming and outgoing data, status lines and handshaking. Here we are using the terms workstation for your computer and modem for the external device, because some signal names (DCD, RI) come from modems. Of course your external device may use these signal lines for other purposes. Live your truth, hardware. ๐
TXD(output) โ Transmitted Data: Outgoing serial data.RXD(input) โ Received Data:Incoming serial data.RTS(output) โ Request To Send: This hardware handshake line informs 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 that the modem is ready to receive data.DTR(output) โ Data Terminal Ready: This signal tells the modem that 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 that the modem is ready to establish a link.DCD(input) โ Data Carrier Detect: This line becomes active when a modem detects a "Carrier" signal.RI(input) โ Ring Indicator: Goes active when the modem detects an incoming call. ๐BREAKโ ABREAKcondition is not a hardware signal line, but a logical zero on theTXDorRXDlines for a long period of time, usually250to500milliseconds. Normally a receive or transmit data signal stays at the mark (on=1) voltage until the next character is transferred. ABREAKis sometimes used to reset the communications line or change the operating mode of communications hardware. It's the "hold up, we need to talk" of the wire world. โ
๐ ERROR CODES (Windows only) ๐
A lot of different errors may occur during serial read operations or during event polling in background. The external device may have been switched off, the data lines may be noisy, system buffers may overrun or your mode settings may be wrong. That is why a reliable software should always catch serial read operations. In cases of an error Tcl returns a general file I/O error. Then fconfigure -lasterror may help to locate the problem. The following error codes may be returned.
RXOVERโ Windows input buffer overrun. The data comes faster than your scripts reads it or your system is overloaded. Usefconfigure -sysbufferto avoid a temporary bottleneck and/or make your script faster. ๐โโ๏ธTXFULLโ Windows output buffer overrun. Complement toRXOVER. This error should practically not happen, because Tcl cares about the output buffer status. Tcl is a good friend like that. ๐ซถ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 error.FRAMEโ A stop-bit error has been detected by your UART. Wrong mode settings withfconfigure -modeor a noisy data line (RXD) may cause this error.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 accepted as well is comX:. This notation only works for serial ports from 1 to 9. An attempt to open a serial port that does not exist or has a number greater than 9 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 entered at the console will be sent to the command pipeline and some will be 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 occur because both Tcl and the child application are competing for the console at the same time. If the command pipeline is started from a script, so that Tcl is not accessing the console, or if the command pipeline does not use standard input or output, but is redirected from or to a file, then the above problems do not occur. ๐ฎโ๐จ
Files opened in the"a"mode or with theAPPENDflag 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 is present on POSIX platforms. Important, no cap.
Unix
Valid values for fileName to open a serial port are generally of the form /dev/ttyX, where X is a or b, but 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 will be sent to the command pipeline and some will be sent to the Tcl evaluator. This problem only occurs because both Tcl and the child application are competing for the console at the same time. If the command pipeline is started from a script, so that Tcl is not accessing the console, or if the command pipeline does not use standard input, but is redirected from a file, then the above problem does not 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 ๐ซง
ok so this part is Windows only bestie, don't come for me. Console channels (which are usually stdin or stdout) support these two options:
-inputmodeinputMode โ use this to query or change the input mode of the console channel, which is the thing that controls how interactive input from users gets handled. Here's what you can pass for inputMode:normalโ says that normal line-oriented input should be used, with the standard console editing capabilities enabled. the classic vibe.passwordโ says that non-echoing input should be used, with standard console editing capabilities enabled but no writing of typed characters to the terminal (except for newlines). sneaky. ๐rawโ says that all keyboard input should be given directly to Tcl with the console doing no processing at all. It does not echo the keys, leaving it up to the Tcl script to interpret what to do. main character energy, you're on your own fr.reset(set only) โ says that the console should be reset to what state it was in when the console channel was opened. time travel, kinda.
Note that setting this option (technically, anything that changes the console state from its default via this option) will cause the channel to turn on an automatic reset of the console when the channel is closed. so it cleans up after itself, periodt.
-winsizeโ this option is query only. It retrieves a two-element list with the current width and height of the console that this channel is talking to. size check ๐ฆ
Note that the equivalent options exist on Unix, but are on the serial channel type. iykyk, different channel, same lore.
โจ EXAMPLES โจ
ok bestie these are the good ones, study them like flashcards ๐
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 non-trivial edge cases with arguments that potentially have spaces in. yes it looks weird. yes it's correct. trust. ๐ฅ
set fl [open |[list create_image_data $input] "rb"]
set binData [read $fl]
close $fl
Read a password securely from the user (assuming that the script is being run interactively):
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 move. never leave the console in password mode, that's a crime ๐
๐ SEE ALSO ๐
file(n), close(n), filename(n), fconfigure(n), gets(n), read(n), puts(n), exec(n), pid(n), fopen(3)
go read those next, they're all part of the same friend group ๐ซถ
๐ KEYWORDS ๐
access mode, append, create, file, non-blocking, open, permissions, pipeline, process, serial
and that's the whole page bestie!! ๐ this one's from Tcl 8.3, the open(n) page โ Tcl's out here still serving after all these years, iconic behavior honestly. go open some files (responsibly) ๐โจ๐ธ
๐ฆ where this page comes from
- alpine 3.23: tcl9-doc 9.0.3-r0 ยท TCL
- alpine 3.24: tcl9-doc 9.0.3-r2 ยท TCL
- fedora 43: tcl-doc 1:9.0.2-1.fc43 ยท TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- fedora 44: tcl-doc 1:9.0.2-1.fc44 ยท TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- nixos 26.05: tcl 9.0.3
- 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