tags:

views:

172

answers:

2

Is there a function in the C Library under Linux which can set the length of a file? Under Windows I know there is a SetFileLength() function. If there is not, what is the best way of shortening a file without deleting and rewriting it?

+5  A: 

You can use the truncate function.

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

From the man page:

"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. If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as null bytes"

codelogic
Thanks, but is this portable?
codymanix
codymanix, it is from POSIX, so it is supposed to be available in POSIX operation systems.
Johannes Schaub - litb
ote that truncate isn't specified for POSIX only systems. it requires XSI conformant systems. on the other side, it says most unices are xsi compliant. so you should be fine with truncate i think.
Johannes Schaub - litb
+3  A: 
   #include <unistd.h>
   #include <sys/types.h>

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

From its manpage:

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.

If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0').

Johannes Schaub - litb