Tcl_OpenFileChannel(3tcl)

omg hey bestie πŸ’– welcome to the Tcl Library Procedures manual page for Tcl_OpenFileChannel(3tcl). It's giving channel I/O realness, and honestly? iconic. ✨

🌸 NAME 🌸

okay so this page is literally the whole squad of buffered I/O facilities using channels. The cast is long, bestie, so buckle up: Tcl_OpenFileChannel, Tcl_OpenCommandChannel, Tcl_MakeFileChannel, Tcl_GetChannel, Tcl_GetChannelNames, Tcl_GetChannelNamesEx, Tcl_RegisterChannel, Tcl_UnregisterChannel, Tcl_DetachChannel, Tcl_IsStandardChannel, Tcl_Close, Tcl_CloseEx, Tcl_ReadChars, Tcl_Read, Tcl_GetsObj, Tcl_Gets, Tcl_WriteObj, Tcl_WriteChars, Tcl_Write, Tcl_Flush, Tcl_Seek, Tcl_Tell, Tcl_TruncateChannel, Tcl_GetChannelOption, Tcl_SetChannelOption, Tcl_Eof, Tcl_InputBlocked, Tcl_InputBuffered, Tcl_OutputBuffered, Tcl_Ungets, Tcl_ReadRaw, Tcl_WriteRaw β€” and that's the whole buffet. periodt. πŸ’…

✨ SYNOPSIS ✨

okay so the synopsis is giving "include this header and then here are all the signatures" vibes. Copy them exactly, no cap. First you gotta #include <tcl.h>, then it's just:

       #include <tcl.h>

       Tcl_Channel
       Tcl_OpenFileChannel(interp, fileName, mode, permissions)

       Tcl_Channel
       Tcl_OpenCommandChannel(interp, argc, argv, flags)

       Tcl_Channel
       Tcl_MakeFileChannel(handle, readOrWrite)

       Tcl_Channel
       Tcl_GetChannel(interp, channelName, modePtr)

       int
       Tcl_GetChannelNames(interp)

       int
       Tcl_GetChannelNamesEx(interp, pattern)

       Tcl_RegisterChannel(interp, channel)

       int
       Tcl_UnregisterChannel(interp, channel)

       int
       Tcl_DetachChannel(interp, channel)

       int
       Tcl_IsStandardChannel(channel)

       int
       Tcl_Close(interp, channel)

       int
       Tcl_CloseEx(interp, channel, closeFlags)

       Tcl_Size
       Tcl_ReadChars(channel, readObjPtr, charsToRead, appendFlag)

       Tcl_Size
       Tcl_Read(channel, readBuf, bytesToRead)

       Tcl_Size
       Tcl_GetsObj(channel, lineObjPtr)

       Tcl_Size
       Tcl_Gets(channel, lineRead)

       Tcl_Size
       Tcl_Ungets(channel, input, inputLen, addAtEnd)

       Tcl_Size
       Tcl_WriteObj(channel, writeObjPtr)

       Tcl_Size
       Tcl_WriteChars(channel, charBuf, bytesToWrite)

       Tcl_Size
       Tcl_Write(channel, byteBuf, bytesToWrite)

       Tcl_Size
       Tcl_ReadRaw(channel, readBuf, bytesToRead)

       Tcl_Size
       Tcl_WriteRaw(channel, byteBuf, bytesToWrite)

       int
       Tcl_Eof(channel)

       int
       Tcl_Flush(channel)

       int
       Tcl_InputBlocked(channel)

       int
       Tcl_InputBuffered(channel)

       int
       Tcl_OutputBuffered(channel)

       long long
       Tcl_Seek(channel, offset, seekMode)

       long long
       Tcl_Tell(channel)

       int
       Tcl_TruncateChannel(channel, length)

       int
       Tcl_GetChannelOption(interp, channel, optionName, optionValue)

       int
       Tcl_SetChannelOption(interp, channel, optionName, newValue)

🫢 ARGUMENTS 🫢

okay so here's the whole cast of characters that shows up in literally every function on this page. bestie, read this once and you're set for the whole API, i prommy. ✨

  • Tcl_Interp *interp (in) β€” the interpreter. it's the one that holds your error messages and it's also how we look up a channel that's been registered in it. no interp, no vibes. πŸ’…
  • const char *fileName (in) β€” the name of a file. local file, network file, we don't discriminate. 🌐
  • const char *mode (in) β€” how the file gets accessed, okay? it can be any of the values that the mode argument to the Tcl open command allows. so go check that list, i'm not retyping it. πŸ™ˆ
  • int permissions (in) β€” POSIX-style permission flags, like 0644. and like, if a brand new file gets created? these permissions get set on it. that's the whole deal. πŸ”
  • Tcl_Size argc (in) β€” how many elements are chillin' in argv. the headcount. πŸ”’
  • const char **argv (in) β€” the args for building a command pipeline. these mean exactly the same thing as the non-switch arguments to the Tcl exec command. no cap. 🚰
  • int flags (in) β€” this one's the disposition of the stdio handles in the pipeline, and it's an OR-ed combo of TCL_STDIN, TCL_STDOUT, TCL_STDERR, and TCL_ENFORCE_MODE. If TCL_STDIN is set, then stdin for the first child in the pipe is the pipe channel β€” otherwise it's the same as the standard input of the invoking process. same energy for TCL_STDOUT and TCL_STDERR, obviously. πŸ’«

and now the spicy part: if TCL_ENFORCE_MODE is not set, the pipe can redirect stdio handles to override the stdio handles for which TCL_STDIN, TCL_STDOUT and TCL_STDERR have been set. if it is set? then such redirections cause an error. periodt. πŸ’€

  • void *handle (in) β€” the OS-specific handle for I/O to a file. on Unix it's a file descriptor; on Windows it's a HANDLE. platform girlies stay winning. πŸ–₯️
  • int readOrWrite (in) β€” an OR-ed combination of TCL_READABLE and TCL_WRITABLE, telling us what operations are actually valid on handle. 🚦
  • const char *channelName (in) β€” the name of the channel. yeah. that's it. short and sweet. πŸŽ€
  • int *modePtr (out) β€” points at an integer variable that's gonna receive an OR-ed combination of TCL_READABLE and TCL_WRITABLE, saying whether the channel is open for reading and writing. it's the output, bestie, it writes back to you. ✍️
  • const char *pattern (in) β€” the pattern to match on. it gets passed to Tcl_StringMatch. or it can be NULL. your call. 🧐
  • Tcl_Channel channel (in) β€” a Tcl channel for input or output. it must have been the return value from a procedure like Tcl_OpenFileChannel. don't just roll up with a random channel, that's not the vibe. ⚠️
  • Tcl_Obj *readObjPtr (in/out) β€” a pointer to a Tcl value where we store the characters read from the channel. in and out. it does both. main character behavior. πŸ‘‘
  • Tcl_Size charsToRead (in) β€” how many characters to read off the channel. and heads up: if the channel's encoding is binary, then this is equivalent to the number of bytes to read from the channel. same number, different unit name, iykyk. 🧠
  • int closeFlags (in) β€” 0 means the channel gets closed in both directions. TCL_CLOSE_READ means it's only closed for reading. TCL_CLOSE_WRITE means it's only closed for writing. πŸšͺ
bestie these flags must NOT be combined. do not. i'm serious. 🚫
  • int appendFlag (in) β€” if it's non-zero, data read from the channel gets appended to the value. otherwise the data replaces whatever was in the value before. bye bye old contents. πŸ—‘οΈ
  • char *readBuf (out) β€” a buffer where the bytes read from the channel get stored. πŸ«™
  • Tcl_Size bytesToRead (in) β€” how many bytes to read from the channel. and the buffer readBuf must be big enough to hold this many bytes, or we're gonna have a bad time. 😭
  • Tcl_Obj *lineObjPtr (in/out) β€” pointer to a Tcl value where the line read from the channel gets stored. and listen β€” the line read gets appended to the current value of the value. it does not overwrite. πŸ“Ž
  • Tcl_DString *lineRead (in/out) β€” a pointer to a Tcl dynamic string where the line read from the channel gets stored. it must have been initialized by the caller first. and the line read gets appended to any data that's already in the dynamic string. same deal as above. 🧡
  • const char *input (in) β€” the input to add to a channel buffer. in goes the input. πŸ“₯
  • Tcl_Size inputLen (in) β€” length of the input. that's the description. it's the length. of the input. πŸ’―
  • int addAtEnd (in) β€” a flag saying whether the input should be added to the end or the beginning of the channel buffer. front or back, pick one. πŸ”„
  • Tcl_Obj *writeObjPtr (in) β€” a pointer to a Tcl value whose contents get output to the channel. πŸ“€
  • const char *charBuf (in) β€” a buffer holding the characters to output to the channel. πŸ”€
  • const char *byteBuf (in) β€” a buffer holding the bytes to output to the channel. note that this one is bytes, not characters. don't mix 'em up. 🧊
  • Tcl_Size bytesToWrite (in) β€” how many bytes to consume from charBuf or byteBuf and output to the channel. 🍽️
  • long long offset (in) β€” how far to move the access point in the channel β€” y'know, the spot where the next input or output operation gets applied β€” measured in bytes from the position given by seekMode. and it may be positive or negative. both directions are valid. 🧭
  • int seekMode (in) β€” relative to which point do we seek? it's used together with offset to calculate the new access point for the channel. legal values are SEEK_SET, SEEK_CUR, and SEEK_END. that's the whole menu. βš–οΈ
  • long long length (in) β€” the (non-negative) length to truncate the channel to. non-negative only, bestie, don't try it. βœ‚οΈ
  • const char *optionName (in) β€” the name of an option that applies to this channel, like -blocking. it may have any of the values accepted by the fconfigure command. πŸŽ›οΈ
  • Tcl_DString *optionValue (in) β€” where to store the value of an option, or a list of all options and their values. it must have been initialized by the caller. πŸ—‚οΈ
  • const char *newValue (in) β€” the new value for the option given by optionName. the glow-up value. ✨

πŸ’– DESCRIPTION πŸ’–

πŸ“Œ N.B. go read the Tcl_UniChar documentation page for a description of the TUTF-8 encoding and all the related terms referenced here. like, actually go read it. it's relevant. πŸ¦‹

okay so. the Tcl channel mechanism?? it's the whole reason this is so good. it gives you a device-independent and platform-independent way to do buffered input and output on a whole buffet of file, socket, and device types. every one of them. same API. iconic. πŸ”₯

and the best part? the channel mechanism is extensible to new channel types β€” you just provide a low-level channel driver for whatever new type you're bringing to the function, and the channel driver interface is described over in the manual entry for Tcl_CreateChannel. so if you want a new kind of channel, you can literally just... build it. slay. 🧚

the channel mechanism also hands you a buffering scheme modeled after Unix's standard I/O (heritage!! πŸ’œ), and it also allows for nonblocking I/O on channels. so you don't have to sit there blocked. we love to see it. 🌈

and for the record: the procedures described in this manual entry make up the C APIs of the generic layer of the channel architecture. if what you actually want is the channel driver architecture, or how to implement channel drivers for new types of channels, then go see the manual entry for Tcl_CreateChannel. different page, different quest. πŸ—ΊοΈ

🌸 TCL_OPENFILECHANNEL 🌸

okay bestie so Tcl_OpenFileChannel opens a file β€” the one you point at with fileName β€” and hands you back a channel handle ✨ that you can use to do input and output on that file. it's giving the Unix standard I/O library's fopen procedure, no cap. the syntax and the meaning of all the arguments are just like the ones in the Tcl open command when you're opening a file. 🫢

if an error happens while opening the channel, Tcl_OpenFileChannel returns NULL and records a POSIX error code that you can retrieve with Tcl_GetErrno. and on top of that, if interp is non-NULL, Tcl_OpenFileChannel leaves an error message in interp's result after any error. thoughtful queen πŸ’…

⚠️ real talk: as of Tcl 8.4, the value-based API Tcl_FSOpenFileChannel should be used in preference to Tcl_OpenFileChannel wherever possible. lowkey just use the new one, bestie.

the freshly created channel is not registered in the interpreter you handed over; to register it, use Tcl_RegisterChannel, described below πŸ“. and if one of the standard channels β€” stdin, stdout or stderr β€” was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. slay, it fills the empty spot ✨


πŸ”₯ TCL_OPENCOMMANDCHANNEL πŸ”₯

Tcl_OpenCommandChannel is the C-level interface to the functions of the exec and open commands, periodt. it creates a sequence of subprocesses specified by the argv and argc arguments and returns a channel that can be used to communicate with those subprocesses. the flags argument is basically the vibe check for what sort of communication will exist with the command pipeline πŸ‘‘

here's the flag tea 🍡:

  • if the TCL_STDIN flag is set, then the standard input for the first subprocess will be tied to the channel: writing to the channel will provide input to the subprocess. if TCL_STDIN is not set, then standard input for the first subprocess will be the same as this application's standard input.
  • if TCL_STDOUT is set, then standard output from the last subprocess can be read from the channel; otherwise it goes to this application's standard output.
  • if TCL_STDERR is set, standard error output for all subprocesses is returned to the channel and results in an error when the channel is closed; otherwise it goes to this application's standard error.
  • if TCL_ENFORCE_MODE is not set, then argc and argv can redirect the stdio handles to override TCL_STDIN, TCL_STDOUT, and TCL_STDERR; if it is set, then it is an error for argc and argv to override stdio channels for which TCL_STDIN, TCL_STDOUT, and TCL_STDERR have been set. like, hands off the ones I already claimed πŸ’€

if an error occurs while opening the channel, Tcl_OpenCommandChannel returns NULL and records a POSIX error code that can be retrieved with Tcl_GetErrno. plus, Tcl_OpenCommandChannel leaves an error message in the interpreter's result. 🚨 and heads up: interp cannot be NULL. fr fr.

the newly created channel is not registered in the supplied interpreter; to register it, use Tcl_RegisterChannel, described below. and same as always β€” if one of the standard channels, stdin, stdout or stderr was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. πŸ’–


πŸ‘‘ TCL_MAKEFILECHANNEL πŸ‘‘

Tcl_MakeFileChannel makes a Tcl_Channel out of an existing, platform-specific, file handle. iconic behavior honestly 🌈

the newly created channel is not registered in the supplied interpreter; to register it, use Tcl_RegisterChannel, described below. and yes bestie, same ritual as before: if one of the standard channels, stdin, stdout or stderr was previously closed, the act of creating the new channel also assigns it as a replacement for the standard channel. ✨


πŸ¦‹ TCL_GETCHANNEL πŸ¦‹

Tcl_GetChannel returns a channel, given the channelName that was used to create it with Tcl_CreateChannel, plus a pointer to a Tcl interpreter in interp. if a channel by that name isn't registered in that interpreter, the procedure returns NULL. πŸ™ˆ

if the modePtr argument is not NULL, it points at an integer variable that will receive an OR-ed combination of TCL_READABLE and TCL_WRITABLE, describing whether the channel is open for reading and writing. so it spills the mode, cute πŸ’…

Tcl_GetChannelNames and Tcl_GetChannelNamesEx write the names of the registered channels to the interpreter's result as a list value. Tcl_GetChannelNamesEx will filter those names according to the pattern. if pattern is NULL, then it will not do any filtering at all. the return value is TCL_OK if no errors occurred writing to the result, otherwise it is TCL_ERROR, and the error message is left in the interpreter's result. πŸ“‹


πŸ’œ TCL_REGISTERCHANNEL πŸ’œ

Tcl_RegisterChannel adds a channel to the set of channels accessible in interp. after this call, Tcl programs executing in that interpreter can refer to the channel in input or output operations using the name that was given in the call to Tcl_CreateChannel. ✨

and here's the part you actually have to remember: after this call, the channel becomes the property of the interpreter, and the caller should not call Tcl_Close for the channel β€” the channel will be closed automatically when it is unregistered from the interpreter. don't be out here closing other people's channels πŸ’€

code executing outside of any Tcl interpreter can call Tcl_RegisterChannel with interp as NULL, to indicate that it wishes to hold a reference to this channel. then the channel can be registered in a Tcl interpreter, and it will only be closed when the matching number of calls to Tcl_UnregisterChannel have been made. this allows code executing outside of any interpreter to safely hold a reference to a channel that is also registered in a Tcl interpreter. best of both worlds fr fr 🫢

this procedure also interacts with the code managing the standard channels. if no standard channels were initialized before the first call to Tcl_RegisterChannel, they will get initialized by that call. see Tcl_StandardChannels for a general treatise about standard channels and the behavior of the Tcl library with regard to them. πŸ“š


πŸŽ€ TCL_UNREGISTERCHANNEL πŸŽ€

Tcl_UnregisterChannel removes a channel from the set of channels accessible in interp. after this call, Tcl programs will no longer be able to use the channel's name to refer to the channel in that interpreter. and if this operation removed the last registration of the channel in any interpreter, the channel is also closed and destroyed. bye bestie πŸ‘‹πŸ’–

code not associated with a Tcl interpreter can call Tcl_UnregisterChannel with interp as NULL, to indicate to Tcl that it no longer holds a reference to that channel. if this is the last reference to the channel, it will now be closed. Tcl_UnregisterChannel is very similar to Tcl_DetachChannel, except that it will also close the channel if no further references to it exist. subtle but iconic difference 🌟


🌈 TCL_DETACHCHANNEL 🌈

Tcl_DetachChannel removes a channel from the set of channels accessible in interp. after this call, Tcl programs will no longer be able to use the channel's name to refer to the channel in that interpreter. beyond that, this command has no further effect.

🚫 it cannot be used on the standard channels (stdout, stderr, stdin), and will return TCL_ERROR if passed one of those channels.

code not associated with a Tcl interpreter can call Tcl_DetachChannel with interp as NULL, to indicate to Tcl that it no longer holds a reference to that channel. if this is the last reference to the channel, unlike Tcl_UnregisterChannel, it will not be closed. so it's like, you let go, but the channel lives on πŸ’…


⭐ TCL_ISSTANDARDCHANNEL ⭐

Tcl_IsStandardChannel tests whether a channel is one of the three standard channels β€” stdin, stdout or stderr. if so, it returns 1, otherwise 0. a lil vibe check, if you will 😌

πŸ™ˆ no attempt is made to check whether the given channel or the standard channels are initialized or otherwise valid. it just answers the question it was asked.

πŸ“ TCL_CLOSE AND TCL_CLOSEEX πŸ“

Tcl_Close destroys the channel channel, which must denote a currently open channel. the channel should not be registered in any interpreter when Tcl_Close is called. buffered output is flushed to the channel's output device prior to destroying the channel, and any buffered input is discarded. πŸ—‘οΈ

  • if this is a blocking channel, the call does not return until all buffered data is successfully sent to the channel's output device.
  • if this is a nonblocking channel and there is buffered output that cannot be written without blocking, the call returns immediately; output is flushed in the background and the channel will be closed once all of the buffered data has been output. in this case, errors during flushing are not reported. πŸ’€

Tcl_CloseEx allows for both full closing and half-closing of channels, depending on its closeFlags parameter. see the description of the parameter above. it is an error to attempt to close the channel for a direction for which it is not open. the channel is destroyed only when it has been closed for both reading and writing. only socket and command pipe channels support half-closing. πŸ”Œ

if the channel was closed successfully, Tcl_Close and Tcl_CloseEx return TCL_OK. if an error occurs, they return TCL_ERROR and record a POSIX error code that can be retrieved with Tcl_GetErrno. if the channel is being closed synchronously and an error occurs during closing of the channel and interp is not NULL, an error message is left in the interpreter's result. 🫢

🚨 and now the big warning, bestie: it is not safe to call the channel closing functions on a channel that has been registered using Tcl_RegisterChannel; see the documentation for Tcl_RegisterChannel, above, for details. if the channel has ever been given as the chan argument in a call to Tcl_RegisterChannel, you should instead use Tcl_UnregisterChannel, which will internally call Tcl_Close when all calls to Tcl_RegisterChannel have been matched by corresponding calls to Tcl_UnregisterChannel. periodt πŸ’…

✨ TCL_READCHARS AND TCL_READ ✨

Okay bestie, gather round, because this is the reading section and it's lowkey the most-used thing in the whole API. πŸ’–

Tcl_ReadChars consumes bytes from channel, converting those bytes to TUTF-8 based on the channel's encoding, and stores the produced data in readObjPtr's string representation. The return value is the number of characters β€” up to charsToRead β€” that got stored in readObjPtr. If an error happens while reading, you get back -1 and Tcl_ReadChars records a POSIX error code that you can grab with Tcl_GetErrno. And if an encoding error happens while the channel is in blocking mode with -profile strict, then the characters retrieved until the encoding error happened will still be stored in readObjPtr. So you don't lose them, no cap. 🫢

Setting charsToRead to -1 makes the command read all characters currently available (that's non-blocking) or everything until eof (that's blocking mode). Main character energy: give me everything or give me nothing.

The return value may be smaller than the value you asked to read, which means less data than requested was available. That's called a short read. In blocking mode this can only happen on an end-of-file. In nonblocking mode, a short read can also occur if an encoding error is encountered (with -profile strict) or if there's not enough input currently available: Tcl_ReadChars returns a short count rather than waiting for more data. She's impatient, she's booked, she's not waiting around. πŸ’…

If the channel is in blocking mode, a return value of 0 indicates an end-of-file condition. If the channel is in nonblocking mode, a return value of 0 indicates either that no input is currently available or an end-of-file condition. Use Tcl_Eof and Tcl_InputBlocked to tell which of these conditions actually occurred. Do not guess, bestie, ask the function. πŸ”₯

Tcl_ReadChars translates the various end-of-line representations into the canonical \n internal representation according to the current end-of-line recognition mode. All the end-of-line recognition tea and the various platform-specific modes are described in the manual entry for the Tcl fconfigure command.

As a performance optimization, when reading from a channel with the encoding binary, the bytes are not converted to TUTF-8 as they are read. Instead, they're stored in readObjPtr's internal representation as a byte-array value. The string representation of this value will only be constructed if it's needed (e.g., because of a call to Tcl_GetStringFromObj). That way, byte-oriented data can be read from a channel, manipulated by calling Tcl_GetByteArrayFromObj and related functions, and then written to a channel without the expense of ever converting to or from TUTF-8. Efficient queen behavior. πŸ‘‘

Tcl_Read is similar to Tcl_ReadChars, except that it does not do encoding conversions, regardless of the channel's encoding. It is deprecated and exists for backwards compatibility with non-internationalized Tcl extensions. It consumes bytes from channel and stores them in readBuf, performing end-of-line translations on the way. The return value of Tcl_Read is the number of bytes, up to bytesToRead, written in readBuf. The buffer produced by Tcl_Read is not null-terminated. Its contents are valid from the zeroth position up to and excluding the position indicated by the return value. Read that twice, it matters. 🚨

Tcl_ReadRaw is the same as Tcl_Read but does not compensate for stacking. While Tcl_Read (and the other functions in the API) always get their data from the topmost channel in the stack the supplied channel is part of, Tcl_ReadRaw does not. So this function is only usable for transformational channel drivers, i.e. drivers used in the middle of a stack of channels, to move data from the channel below into the transformation. It's giving backstage pass, not front row. πŸŽ€


✨ TCL_GETSOBJ AND TCL_GETS ✨

Line-by-line reads, the cozy era of the API. 🌸

Tcl_GetsObj consumes bytes from channel, based on the channel's encoding, until a full line of input has been seen. If the channel's encoding is binary, each byte read from the channel is treated as an individual Unicode character. All of the characters of the line, except for the terminating end-of-line character(s), are appended to lineObjPtr's string representation. The end-of-line character(s) are read and discarded. Bye bye, newline, you did your job. πŸ¦‹

If a line was successfully read, the return value is greater than or equal to zero and indicates the number of bytes stored in lineObjPtr. If an error occurs, Tcl_GetsObj returns -1 and records a POSIX error code that can be retrieved with Tcl_GetErrno. Tcl_GetsObj also returns -1 if the end of the file is reached; the Tcl_Eof procedure can be used to distinguish an error from an end-of-file condition. Same energy as before: don't assume, check. πŸ’€

If the channel is in nonblocking mode, the return value can also be -1 if no data was available or the data that was available did not contain an end-of-line character. When -1 is returned, the Tcl_InputBlocked procedure may be invoked to determine if the channel is blocked because of input unavailability. Look at her juggling so many meanings for one little -1. Iconic, honestly. ⭐

Tcl_Gets works similarly to Tcl_GetsObj except the read bytes are appended as a TUTF-8 encoded byte sequence to the dynamic string given by lineRead rather than a Tcl value.


✨ TCL_UNGETS ✨

Putting things back. The rewind button of the channel world. πŸ™ˆ

Tcl_Ungets is used to add data to the input queue of a channel, at either the head or the tail of the queue. The pointer input points to the data that is to be added. The length of the input to add is given by inputLen. A non-zero value of addAtEnd indicates that the data is to be added at the end of queue; otherwise it will be added at the head of the queue. If channel has a "sticky" EOF set, no data will be added to the input queue. Tcl_Ungets returns inputLen, or -1 if an error occurs.


✨ TCL_WRITECHARS, TCL_WRITEOBJ, AND TCL_WRITE ✨

The writing girlies. Let's talk output. πŸ’œ

Tcl_WriteChars accepts bytesToWrite bytes of character data at charBuf. The TUTF-8 encoded bytes in the buffer are converted to the channel's encoding and queued for output to channel. If bytesToWrite is negative, Tcl_WriteChars expects charBuf to be null-terminated and it outputs everything up to the null.

Data queued for output may not appear on the output device immediately, because of internal buffering. If the data should appear immediately, call Tcl_Flush after the call to Tcl_WriteChars, or set the -buffering option on the channel to none. If you want the data to appear as soon as a complete line is accepted for output, set the -buffering option on the channel to line mode. Choose your vibe. ✨

The return value of Tcl_WriteChars is a count of how many bytes were accepted for output to the channel. This is either -1 to indicate that an error occurred, or another number greater than zero to indicate success. If an error occurs, Tcl_WriteChars records a POSIX error code that may be retrieved with Tcl_GetErrno.

Newline characters in the output data are translated to platform-specific end-of-line sequences according to the -translation option for the channel. This is done even if the channel has no encoding. Yes bestie, even then. 🌈

Tcl_WriteObj is similar to Tcl_WriteChars except it accepts a Tcl value whose contents will be output to the channel. The characters in writeObjPtr's string representation are converted to the channel's encoding and queued for output to channel. As a performance optimization, when writing to a channel with the encoding binary, characters are not converted as they are written. Instead, the bytes in writeObjPtr's internal representation as a byte-array value are written to the channel. The byte-array representation of the value will be constructed if it is needed. In this way, byte-oriented data can be read from a channel, manipulated by calling Tcl_GetByteArrayFromObj and related functions, and then written to a channel without the expense of encoding conversion. It's the same efficiency flex as Tcl_ReadChars, just the other direction. πŸ‘‘

Tcl_Write is similar to Tcl_WriteChars except that it does not do encoding conversions, regardless of the channel's encoding. It is deprecated and exists for backwards compatibility with non-internationalized Tcl extensions. It accepts bytesToWrite bytes of data at byteBuf and queues them for output to channel. If bytesToWrite is negative, Tcl_Write expects byteBuf to be null-terminated and it outputs everything up to the null.

Tcl_WriteRaw is the same as Tcl_Write but does not compensate for stacking. While Tcl_Write (and the other functions in the API) always feed their input to the topmost channel in the stack the supplied channel is part of, Tcl_WriteRaw does not. So this function is only usable for transformational channel drivers, i.e. drivers used in the middle of a stack of channels, to move data from the transformation into the channel below it. Certified mid-stack-only behavior. πŸŽ€


✨ TCL_FLUSH ✨

Tcl_Flush causes all of the buffered output data for channel to be written to its underlying file or device as soon as possible. If the channel is in blocking mode, the call does not return until all the buffered data has been sent to the channel or some error occurred. The call returns immediately if the channel is nonblocking; it starts a background flush that will write the buffered data to the channel eventually, as fast as the channel is able to absorb it. Set it and forget it, but like, responsibly. πŸ’…

The return value is normally TCL_OK. If an error occurs, Tcl_Flush returns TCL_ERROR and records a POSIX error code that can be retrieved with Tcl_GetErrno.


✨ TCL_SEEK ✨

Tcl_Seek moves the access point in channel to where subsequent data will be read or written. Buffered output is flushed to the channel and buffered input is discarded, prior to the seek operation. Important order of operations, don't skip it. πŸ”₯

Tcl_Seek normally returns the new access point. If an error occurs, Tcl_Seek returns -1 and records a POSIX error code that can be retrieved with Tcl_GetErrno. After an error, the access point may or may not have been moved. Ma'am, that's a real caveat β€” don't assume you're where you think you are after a failure. 😭


✨ TCL_TELL ✨

Tcl_Tell returns the current access point for a channel. The returned value is -1 if the channel does not support seeking.


✨ TCL_TRUNCATECHANNEL ✨

Tcl_TruncateChannel truncates the file underlying channel to a given length of bytes. It returns TCL_OK if the operation succeeded, and TCL_ERROR otherwise. Short. Sweet. Gives you exactly what you need and nothing else. πŸ“


✨ TCL_GETCHANNELOPTION ✨

Tcl_GetChannelOption retrieves, in optionValue, the value of one of the options currently in effect for a channel β€” or a whole list of all options and their values. The channel argument identifies the channel for which to query an option or retrieve all options and their values. If optionName is not NULL, it's the name of the option to query, and the option's value is copied to the Tcl dynamic string denoted by optionValue. If optionName is NULL, the function stores an alternating list of option names and their values in optionValue, using a series of calls to Tcl_DStringAppendElement. Served family style. 🧚

The various preexisting options and their possible values are described in the manual entry for the Tcl fconfigure command. Other options can be added by each channel type. These channel type specific options are described in the manual entry for the Tcl command that creates a channel of that type; for example, the additional options for TCP-based channels are described in the manual entry for the Tcl socket command. iykyk. πŸ’–

The procedure normally returns TCL_OK. If an error occurs, it returns TCL_ERROR and calls Tcl_SetErrno to store an appropriate POSIX error code.

✨ TCL_SETCHANNELOPTION ✨

Tcl_SetChannelOption sets a brand new value newValue for an option optionName on channel. πŸ’… Normally it comes back with TCL_OK like the good little function it is. But if something goes sideways, it returns TCL_ERROR β€” and on top of that, if interp is non-NULL, Tcl_SetChannelOption leaves an error message sitting pretty in the interpreter's result. 🫢


✨ TCL_EOF ✨

Tcl_Eof returns a nonzero value if channel hit an end of file during the last input operation. That's it, that's the whole vibe. πŸ¦‹


✨ TCL_INPUTBLOCKED ✨

Tcl_InputBlocked returns a nonzero value if channel is in nonblocking mode and the last input operation returned less data than requested, because there just wasn't enough data available. 😭 And if the channel is in blocking mode? The call always returns zero. No notes. πŸ’€


✨ TCL_INPUTBUFFERED ✨

Tcl_InputBuffered hands you the number of bytes of input currently buffered in the internal buffers for a channel. Little heads up though: if the channel is not open for reading, this function always returns zero. Periodt. ✨


✨ TCL_OUTPUTBUFFERED ✨

Tcl_OutputBuffered gives you the number of bytes of output currently chillin' in the internal buffers for a channel. And same energy as its sibling: if the channel is not open for writing, this function always returns zero. πŸŽ€


🌈 PLATFORM ISSUES 🌈

The handles you get back from Tcl_GetChannelHandle depend on the platform and the channel type. Fr fr.

  • On Unix platforms, the handle is always a Unix file descriptor as returned from the open system call. 🐧
  • On Windows platforms, the handle is a file HANDLE when the channel was created with Tcl_OpenFileChannel, Tcl_OpenCommandChannel, or Tcl_MakeFileChannel. πŸͺŸ
  • Other channel types may return a totally different type of handle on Windows platforms. So don't assume, bestie. πŸ™ˆ

πŸ‘‘ REFERENCE COUNT MANAGEMENT πŸ‘‘

Okay this part is the main character section, listen up, because getting your reference counts wrong is lowkey how you summon a segfault. πŸ’€

The readObjPtr argument to Tcl_ReadChars must be an unshared value β€” it's going to get modified by this function. Using the interpreter result for this purpose is strongly not recommended. The preferred pattern is to grab a new value from Tcl_NewObj to receive the data, and only pass it along to Tcl_SetObjResult if this function succeeds. ✨

The lineObjPtr argument to Tcl_GetsObj must be an unshared value β€” it will be modified by this function too. Using the interpreter result for this purpose is strongly not recommended. The preferred pattern is, again, a new value from Tcl_NewObj to receive the data, and only pass it to Tcl_SetObjResult if this function succeeds. 🫢

The writeObjPtr argument to Tcl_WriteObj should be a value with any reference count. This function will not modify the reference count. Using the interpreter result without adding an additional reference to it is not recommended. πŸ’…

bestie if you remember nothing else from this entire manpage, remember that unshared-value rule. it's giving "I read the docs" energy and we love that for you πŸŽ€

🌸 SEE ALSO 🌸


⭐ KEYWORDS ⭐

access point, blocking, buffered I/O, channel, channel driver, end of file, flush, input, nonblocking, output, read, seek, write


And that's a wrap on the whole thing, bestie!! πŸŽ‰ You just read the entire Tcl_OpenFileChannel(3tcl) page and honestly? Iconic. πŸ‘‘

This edition is from Tcl 8.3, and the page is dated all the way back with Tcl_OpenFileChannel(3tcl) chillin' in the footer as the source name. Now go forth, open some file channels, and slay. πŸ’–πŸ¦‹βœ¨

πŸ“¦ where this page comes from