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 themodeargument to the Tclopencommand allows. so go check that list, i'm not retyping it. πint permissions(in) β POSIX-style permission flags, like0644. 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' inargv. 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 Tclexeccommand. no cap. π°int flags(in) β this one's the disposition of the stdio handles in the pipeline, and it's an OR-ed combo ofTCL_STDIN,TCL_STDOUT,TCL_STDERR, andTCL_ENFORCE_MODE. IfTCL_STDINis 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 forTCL_STDOUTandTCL_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 aHANDLE. platform girlies stay winning. π₯οΈint readOrWrite(in) β an OR-ed combination ofTCL_READABLEandTCL_WRITABLE, telling us what operations are actually valid onhandle. π¦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 ofTCL_READABLEandTCL_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 toTcl_StringMatch. or it can beNULL. your call. π§Tcl_Channel channel(in) β a Tcl channel for input or output. it must have been the return value from a procedure likeTcl_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) β0means the channel gets closed in both directions.TCL_CLOSE_READmeans it's only closed for reading.TCL_CLOSE_WRITEmeans 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 bufferreadBufmust 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 fromcharBuforbyteBufand 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 byseekMode. 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 withoffsetto calculate the new access point for the channel. legal values areSEEK_SET,SEEK_CUR, andSEEK_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 thefconfigurecommand. ποΈ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 byoptionName. 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 APITcl_FSOpenFileChannelshould be used in preference toTcl_OpenFileChannelwherever 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_STDINflag 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. ifTCL_STDINis not set, then standard input for the first subprocess will be the same as this application's standard input. - if
TCL_STDOUTis 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_STDERRis 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_MODEis not set, thenargcandargvcan redirect the stdio handles to overrideTCL_STDIN,TCL_STDOUT, andTCL_STDERR; if it is set, then it is an error forargcandargvto override stdio channels for whichTCL_STDIN,TCL_STDOUT, andTCL_STDERRhave 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 returnTCL_ERRORif 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 usingTcl_RegisterChannel; see the documentation forTcl_RegisterChannel, above, for details. if the channel has ever been given as thechanargument in a call toTcl_RegisterChannel, you should instead useTcl_UnregisterChannel, which will internally callTcl_Closewhen all calls toTcl_RegisterChannelhave been matched by corresponding calls toTcl_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
opensystem call. π§ - On Windows platforms, the handle is a file
HANDLEwhen the channel was created withTcl_OpenFileChannel,Tcl_OpenCommandChannel, orTcl_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
- ubuntu stonking: tcl9.0-doc 9.0.4+dfsg-1
- Copyright (c) 1996-1997 Sun Microsystems, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms