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.