truncate() — Truncate a file to a specified length

Standards

Standards / Extensions C or C++ Dependencies

XPG4.2
Single UNIX Specification, Version 3

both  

Format

#define _XOPEN_SOURCE_EXTENDED 1
#include <unistd.h>

int truncate(const char *path, off_t length);

General description

Truncates the file indicated by the path to the indicated length. The calling process must have write permission for the file. If the file size exceeds length, any extra data is discarded. If the file size is smaller than length, bytes between the old and new lengths are read as zeros. A change to the size of the file has no impact on the file offset.

If truncate() would cause the file size to exceed the soft file size limit for the process, truncate() will fail and a SIGXFSZ signal will be generated for the process.

If successful, truncate() marks the st_ctime and st_mtime fields of the file.

If unsuccessful, the file is unchanged.

Large file support for z/OS UNIX files: Large z/OS UNIX files are supported automatically for AMODE 64 C/C++ applications. AMODE 31 C/C++ applications must be compiled with the option LANGLVL(LONGLONG) and define the _LARGE_FILES feature test macro before any headers are included to enable this function to operate on z/OS UNIX files that are larger than 2 GB in size. File size and offset fields are enlarged to 63 bits in width. Therefore, any other function operating on the file is required to define the _LARGE_FILES feature test macro as well.

Returned value

If successful, truncate() returns 0.

If unsuccessful, truncate() returns -1 and sets errno to one of the following values:
Error Code
Description
EFBIG
The length argument was greater than the maximum file size.
EINTR
A signal was caught during execution
EINVAL
path does not refer to a regular file, or the length specified is incorrect.
EIO
An I/O error occurred while reading from or writing to a file system.
EISDIR
The file specified is a directory. The system cannot perform the requested function on a directory.
EROFS
The file resides on a read-only file system.

Related information