#include <unistd.h>
#include <sys/types>
int truncate (const char *path, off_t length);
int ftruncate (int fd,off_t length);
The truncate and ftruncate function cause the regular file named by path or referenced by FD to is truncated to a size of Precisely
Length bytes.
The/*truncate and Ftruncate functions are named by the parameter path or by a regular file pointed to by the parameter fd to a byte of the specified size of the parameter length */
If the file previously was larger then this size, the extra data is lost. If the file previously was shorter, it's extended, and the extended
Part reads as null bytes (' + ').
/* If the original file is larger than the specified size, the excess data is lost. If the original file is smaller, it will be enlarged and the enlarged part read as a null character */
The file offset is not changed.
/* file pointer does not change */
If the size changed, then the St_ctime and St_time fields for the file is update, and the Set-usr-id and Set-group-id PE Rmission bits May
Be cleared.
/* If the size changes, the St_ctime and St_time members of the file will be updated, Set-usr-id and Set-group-id bits may be cleared */
On success-returned, on Error-1 are returned and errno is set appropriately.
/* successfully returned 0. Failed to return 1 and set the appropriate error number errno*/
With Ftruncate (), the file must is open for writing; With truncate. The file must be writable.
/* To be writable, the file's open mode must contain a write tag */
Simple example:
int main ()
{
struct STAT st;
int fd = open ("B.txt", o_creat| O_RDWR);
Or O_wronly, when the new file size is 0
Ftruncate (fd,10);
To expand a file to 10 bytes
/* Here you can add write code */
Fstat (FD,&ST);
printf ("Size of File is%d", st.st_size);
Close (FD);
Truncate ("B.txt", 5);
Truncate the file to a size of 5 bytes, and the extra 5 bytes will be discarded
Stat ("B.txt", &st);
printf ("Size of File is%d", st.st_size);
return 0;
}
Linux-function-truncate;