ftruncate(change file size) define function int
ftruncate(int fd,off_t length); function description
ftruncate() changes the file size specified by the parameter fd to the size specified by parameter length. The parameter fd is an open file descriptor and must be a file opened in write mode. If the original file size is larger than the parameter length, then the excess will be deleted. The return value executes successfully, returning 0, failing back to 1, and the cause of the error is stored in errno. Error code EBADF parameter FD file description Word is invalid or the file is closed. EINVAL parameter FD is a socket not a file, or the file is not opened in write mode.
Today with ftruncate truncation file, but how can not achieve the expected effect, truncated after the content of the file is miscellaneous, and the file size is also kept original.
Add Fflush () and rewind () after OK.
Here is the test code:
http://blog.csdn.net/dengzhaoqun/article/details/7962704
[CPP]View Plaincopy
- #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 runs, the contents of the TMP file are end and the size is 4 bytes.
- - - - - - - - - -
It is also OK to use rewind () before calling Ftruncate ().
But with ftruncate () truncated files, in the use of fread, fwrite copy to another file, there will be garbled and some ' \ s ' characters. Switching to fgets and fputs is normal.
Ftruncate (change file size)