Reprint: http://blog.csdn.net/a_ran/article/details/43562429
int truncate (const char *path, off_t length);
int ftruncate (int fd, off_t length);
Change the file size to the size specified by the parameter length, if the original file size is larger than the parameter length, then the excess portion will be deleted, if the original file size is smaller than the parameter length, the file will be expanded,
Similar to the Lseek system call, the extended portion of the file is populated with 0. If the size of the file is changed, the file's St_time and St_ctime will be updated.
If the file previously was larger than this size, the extra data is
Lost. If the file previously was shorter, it's extended, and the
Extended part reads as null bytes (' + ').
The file offset is not changed.
The open file is emptied and then re-written to the requirements, but using ftruncate (FD, 0), and did not achieve the effect, but the file head has ' "", the length is larger than expected.
The reason is that the file offset is not reset using Lseek
int FD;
const char *S1 = "0123456789";
const char *S2 = "ABCDE";
FD = open ("Test.txt", O_creat | o_wronly | O_trunc, 0666);
Write (FD, S1, strlen (S1));
Ftruncate (FD, 0);
Lseek (FD, 0, Seek_set);
Write (FD, S2, strlen (S2));
Close (FD);
return 0;
Empty the file first, then set the file offset, otherwise it will create a file hole
Ftruncate (FD, 0);
Lseek (FD, 0, Seek_set);
Linux C ftruncate function Empty file considerations (to reset offsets using Lseek)