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 ('\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); 

 

转载于:https://www.cnblogs.com/zhangxuan/p/6323281.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值