TIP 206: Add an [ftruncate] Command

Login
Author:         Joe Mistachkin <[email protected]>
State:          Rejected
Type:           Project
Vote:           Done
Created:        25-Jun-2004
Post-History:   
Tcl-Version:    8.5
Obsoleted-By:	208

Abstract

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

Note

This TIP has been effectively rolled into [208].

Rationale

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.

Specification

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.

Copyright

This document has been placed in the public domain.