Linux C ftruncate function Empty file considerations (to reset offsets using Lseek)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.