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.