Fflush () is required before ftruncate () is used in C, and rewind () is required after use ()

Source: Internet
Author: User
Tags rewind tmp file truncated

Today, ftruncate is used to truncate the file, but it cannot achieve the expected results. After the file is truncated, the content is complex and the file size remains unchanged.

After adding fflush () and rewind (), OK.

The following is the test code:

# Include <stdio. h> # include <sys/types. h> # include <unistd. h> int main () {file * FP; char * file = "tmp"; int I; int FD; FP = fopen (file, "W "); if (FP = NULL) {printf ("fopen failed \ n"); Return-1 ;}for (I = 0; I <1000; I ++) {fprintf (FP, "% d -- abcedfg \ n", I) ;}fflush (FP); FD = fileno (FP); If (ftruncate (FD, 0) <0) {perror (""); Return-1;} rewind (FP); fprintf (FP, "end \ n"); fclose (FP); Return 0 ;}

After the program is run, the content of the tmp file is end and the size is 4 bytes.

----------

Use rewind () before calling ftruncate.

However, when you use fread and fwrite to copy a file that has been truncated by ftruncate (), garbled characters and '\ 0' characters may occur. If you use fgets and fputs to copy it to another file, it is normal.

Related Article

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.