转载:http://blog.csdn.net/a_ran/article/details/43562429

 

int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);

将文件大小改变为参数length指定的大小,如果原来的文件大小比参数length大,则超过的部分会被删除,如果原来的文件大小比参数length小,则文件将被扩展,

与lseek系统调用类似,文件的扩展部分将以0填充。如果文件的大小被改变了,则文件的st_time 和st_ctime将会更新。

If the file previously was larger 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.

 

打开的文件清空,然后重新写入的需求,但是使用 ftruncate(fd, 0)后,并没有达到效果,反而文件头部有了'\0',长度比预想的大了。

究其原因是没有使用 lseek 重置文件偏移量

 

int fd;

const char *s1 = "0123456789";
const char *s2 = "abcde";

fd = open("test.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);

write(fd, s1, strlen(s1));

ftruncate(fd, 0);
lseek(fd, 0, SEEK_SET);

write(fd, s2, strlen(s2));

close(fd);

return 0;

 

//先清空文件,再设置文件偏移量,否则会产生文件空洞

ftruncate(fd, 0); 
lseek(fd, 0, SEEK_SET); 

 

posted on 2017-01-20 16:51  邶风  阅读(9503)  评论(0编辑  收藏  举报