Based on the use of ftruncate of in c before the need for fflush of after the use of rewind of in depth discussion

  • 2020-04-02 00:56:04
  • OfStack

Today with ftruncate Truncate the file, but how can not achieve the expected effect, truncated after the content of the file is more miscellaneous, and the file size remains the original.
OK after adding fflush() and rewind().
Here 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 failedn");
  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, "endn");
 fclose(fp);
 return 0;
}

After the program runs, the contents of the TMP file are end and the size is 4 bytes.
- - - - - - - - - -
Rewind () is also fine before calling ftruncate().
However, when files truncated with ftruncate() are copied to another file with fread, fwrite, garbled and some '\0' characters will appear. Use fgets and fputs instead.

Related articles: