|
Before the opening of a document to be emptied, and then re-written demand, but the use of ftruncate (fd, 0), and did not achieve the effect, but the document has a head '\ 0', the length of the larger than expected. The reason is not using lseek reset file offset, I was too naive, and that empty file will be written from scratch.
First man ftruncate Look at the help manual
NAME
Truncate, ftruncate - truncate a file to a specified length
SYNOPSIS
Int truncate (const char * path, off_t length);
Int ftruncate (int fd, off_t length);
DESCRIPTION
The truncate () and ftruncate () functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes.
If the file previously was smaller than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as null bytes ( '\ 0').
The file offset is not changed.
If the size changed, then the st_ctime and st_mtime fields (respectively, time of last status change and time of last modification; see stat (2)) for the file are updated, and the set-user-ID and
Set-group-ID permission bits may be cleared.
With ftruncate (), the file must be open for writing; with truncate (), the file must be writable.
Before that is because I did not see the red line that led to the beginning of the paper I have the wrong paper said that the document will not change the offset!
The experiment is as follows:
#include < stdio.h>
#include < string.h>
#include < unistd.h>
#include < sys / types.h>
#include < sys / stat.h>
#include < fcntl.h>
Int main (void)
{
Int fd;
Const char * s1 = "0123456789";
Const char * s2 = "abcde";
Fd = open ( "test.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
/ * If error * /
Write (fd, s1, strlen (s1)),
Ftruncate (fd, 0);
// lseek (fd, 0, SEEK_SET);
Write (fd, s2, strlen (s2));
Close (fd);
Return 0;
}}
in conclusion:
From the above two pictures, you can see, do not lseek the file size is 15, with hexadecimal format to see xxd see the file header has 10 '\ 0' fill.
And reset the file offset, the file size is 5, the content is correct.
Therefore, when using ftruncate function, re-write must re-set the file offset (ftruncate before or after the line, with lseek or rewind can be). |
|
|
|