truncate, ftruncate - truncate a file to a specified length
int ftruncate(int fd, off_t length);
ftruncate(2) causes the file referenced by fd to be truncated to at most length bytes in size. If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes. With ftruncate(2), the file must be open for writing.
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
- The fd is not a valid descriptor.
- The fd references a socket, not a file. (what happens if you call it on a pipe?)
- The fd is not open for writing.
- The named file is not writable by the user.
- The named file is a directory.
- The named file resides on a read-only file system.
- The file is a pure procedure (shared text) file that is being executed.
- An I/O error occurred updating the inode.
- Path points outside the process's allocated address space.
4.4BSD, SVr4 (these function calls first appeared in BSD 4.2). SVr4 documents for ftruncate(2) additional EAGAIN and EINTR error conditions. POSIX has ftruncate(2) but not truncate(2).
The POSIX standard does not define what happens if the file has fewer bytes than length.
These calls should be generalized to allow ranges of bytes in a file to be discarded.