Truncating Files

You have already seen that the open(2) and creat(2) calls are capable of truncating an existing file. There are times when it is necessary to empty a file of its contents at some later point after the file is open. In other situations, perhaps you simply want to shorten the file because you have compacted your file. To perform these functions, you can call upon the truncate(2) and ftruncate(2) functions.

The truncate(2) Function

The truncate(2) function does not work with an open file. Instead, it allows you to truncate a file without actually opening it. The function synopsis is as follows:

#include <unistd.h>

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

Quite simply, you supply a pathname and the size in bytes that you want ...

Get Advanced UNIX Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.