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 it to be (this is equivalent to specifying the length of the offset at which to truncate). The function returns zero if it is successful; otherwise -1 is returned (with errno).

To force a file to become an empty file (zero bytes), you would call

int z;

z = truncate(pathname,0);
if ( z == -1 )
    /* Report error */

Warning

On some UNIX platforms, the error EINTR can be returned by truncate(2).


Tip

On some UNIX platforms, the function truncate(2) is documented under truncate(3C) instead.


The ftruncate(2) Function

The truncate(2) function performs the function of truncation well, but it proves to be inconvenient at times. If you have written some form of data management library, you may have the file descriptor given to your function as an argument. However, you will not have the pathname necessary for the call to truncate(2). The ftruncate(2) function comes to the rescue, since it works with open files:

#include <unistd.h>

int ftruncate(int fildes, off_t length);

The file that is truncated is specified by the file descriptor fildes. Otherwise, the function is identical to the truncate(2) function. To force the file open on fd to become an empty file, you would code

int z;                 /* Return status */
int fd;                /* Open file descriptor */
z = ftruncate(fd,0);
if ( z == -1 )
    /* Report Error */

When files are written, they are enlarged automatically by the UNIX kernel, as needed. The truncate system calls are the only way you can shorten the length of a file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.186.201