Based on the use of Ftruncate () in C before the need for Fflush (), after the use of the need for rewind () in-depth discussion _c language

Source: Internet
Author: User
Tags rewind tmp file truncated
Today with ftruncateTruncation of the file, but how can not achieve the expected effect, truncated after the contents of the file is miscellaneous, and the file size is kept original.
add fflush () and Rewind () after OK.
Here is the test code:
Copy Code code as follows:

#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 contents of the TMP file is end and the size is 4 bytes.
- - - - - - - - - -
You can use Rewind () before calling Ftruncate ().
However, with ftruncate () truncated files, in the use of fread, fwrite copy to another file, there will be garbled and some ' "" characters. Switching to fgets and fputs is normal.

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.