Linux C ftruncate 函数清空文件注意事项(要使用 lseek 重置偏移量)

转载: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 ('').

The file offset is not changed.

打开的文件清空,然后重新写入的需求,但是使用 ftruncate(fd, 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); 

原文地址:https://www.cnblogs.com/zhangxuan/p/6323281.html