If you want to preserve the previous contents
of the file up to some length (a length bigger than zero, which the
other answers provide), then POSIX provides the truncate()
and ftruncate()
functions for the job.
#include <unistd.h>
int ftruncate(int fildes, off_t length);
int truncate(const char *path, off_t length);
The name indicates the primary purpose - shortening a file. But if
the specified length is longer than the previous length, the file grows
(zero padding) to the new size. Note that ftruncate()
works on a file descriptor, not a FILE *
; you could use:
if (ftruncate(fileno(fp), new_length) != 0) ...error handling...
It is likely, though, that for your purposes, truncate on open is all you need, and for that, the options given by others will be sufficient.
RECENT COMMENT