TIP #206: Add an [ftruncate] Command

Title:Add an [ftruncate] Command
Version:$Revision: 1.5 $
Author:Joe Mistachkin <joe at mistachkin dot com>
Created:Friday, 25 June 2004
Obsoleted-By:TIP #208


This TIP proposes a new command ftruncate for truncating open files.


This TIP has been effectively rolled into TIP #208.


In Tcl, there is currently no way to truncate a file while it is open even though all modern operating systems support such an operation. The current workaround is to close the file and reopen it. However, in cases where the file must be held open (e.g. on Unix where the file has already been deleted and is just being used as scratch space) this workaround cannot be used.


ftruncate channelId ?length?

The channel specified by channelId must refer to a file that was opened for writing. The length argument must be greater than or equal to zero and can be bigger than the current size of the file. If the length argument is omitted, the file will be truncated at the current access position. This command will return any errors received from the operating system.

Example Usage

# Open the file for reading and writing...
set file [open "test.txt" {RDWR}]
# Write some data to the file...
puts $file "test data"

# Some time later...
# ... ... ...
ftruncate $file
# ... ... ...

# We are done, close the file...
close $file

Proposed C API Changes

A new function named Tcl_TruncateChannel would be added to the Tcl C API (taking two arguments, the channel to truncate and the length (as a wide integer to facilitate use with large files) to truncate it to in bytes). The channel API would be modified to add the new functionality for standard disk file channels and to allow extension authors to implement it for their custom channel types through specifying in their Tcl_ChannelType structure a value for the new field truncateProc (of type pointer to Tcl_DriverTruncateProc, which will be a function with the obvious type signature). Finally, the maximum TCL_CHANNEL_VERSION would be increased to TCL_CHANNEL_VERSION_4 to accommodate this new field.

Reference Implementation

A reference implementation does not yet exist.


This document has been placed in the public domain.

Powered by Tcl[Index] [History] [HTML Format] [Source Format] [LaTeX Format] [Text Format] [XML Format] [*roff Format (experimental)] [RTF Format (experimental)]

TIP AutoGenerator - written by Donal K. Fellows