Function like SetFileLength () in C Library for Linux

Is there a function in the C Library under Linux that can set the length of a file? On Windows, I know there is a SetFileLength () function. If it doesn't, what is the best way to shrink the file without deleting and overwriting it?

0


source to share


2 answers


You can use the truncate function .

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



From the man page:

"The truncate () and ftruncate () functions cause a regular file named by path or referring to fd to be truncated to exactly the length of bytes. If the file was previously larger than this size, additional data is lost. If the file was previously shorter, it is expanded and the extended part is read as null bytes "

+5


source


   #include <unistd.h>
   #include <sys/types.h>

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

      

From his man page:



The truncation () and ftruncate () functions call a regular file named by path or by reference fd is truncated to exactly the length of the bytes.

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

+3


source







All Articles