Do typical system call interfaces allow reducing the size of a file (without replacing it with a different inode)?
man -s 2 ftruncate
says
DESCRIPTION
The truncate() and ftruncate() functions cause the regular file
named by path or referenced by fd to be truncated to a size of precisely
length bytes.
...
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, 4.4BSD, SVr4 (these calls first appeared in 4.2BSD).
it goes on to say that if you use ftruncate you must have opened the file for writing, and if you use truncate the file must be writable.
The open(2)
system call accepts the O_TRUNC
flag that can reduce file size:
O_TRUNC
– If the file exists and is a regular file, and the file is successfully openedO_RDWR
orO_WRONLY
, its length shall be truncated to 0, and the mode and owner shall be unchanged. It shall have no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-defined. The result of usingO_TRUNC
without eitherO_RDWR
orO_WRONLY
is undefined.
It is frequently used when the program aims to overwrite the content of a file entirely. An example is your shell’s file redirection operator as in command > file
.