19-文件截断与 truncate 函数

所谓的截断,就是把一个文件的尾部砍掉。truncate 函数可以非常容易的做到这一点。它的原型如下:

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

1 truncate 函数示例

下面给一个简单的示例来说明。这段代码的功能是将指定文件截断成固定长度。

  • 代码
// 文件名: mytruncate.c
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
  char* filename = argv[1];
  int length = atoi(argv[2]);
  truncate(filename, length);
  return 0;
}
  • 编译
gcc mytruncate.c -o mytruncate

2 测试

  • 创建测试文件
$ echo hello > test.txt
$ cat test.txt
hello
  • 截短测试
$ ./mytruncate test.txt 3
$ cat test.txt
hel$ // 结尾的换行没有了
  • 截长测试
$ ./mytruncate test.txt 10

$ ls -l test.txt
-rw-rw-r-- 1 allen allen 10 121 18:24 test.txt

$ hexdump -C test.txt
00000000  68 65 6c 00 00 00 00 00  00 00                    |hel.......|
0000000a

可以发现,截长后,文件后面填充的是 16 进制的 00. 注意,这是依赖操作系统的。

$ ./mytruncate test.txt 10000

$ ls -l test.txt
-rw-rw-r-- 1 allen allen 10000 121 18:27 test.txt

$ stat test.txt
  文件:'test.txt'
  大小:10000           块:8          IO 块:4096   普通文件
设备:801h/2049d        Inode:1050207     硬链接:1
权限:(0664/-rw-rw-r--)  Uid:( 1000/   allen)   Gid:( 1000/   allen)
最近访问:2016-12-01 18:24:53.524715366 +0800
最近更改:2016-12-01 18:27:38.504819061 +0800
最近改动:2016-12-01 18:27:38.504819061 +0800
创建时间:-

虽然截长到 10000 个字节,文件的长度是 10000 字节,但是文件占用的 block 块只有 8 个。这多余部分就是一个空洞,并不占用实际的物理磁盘。

3 总结

  • 掌握 truncate 函数的用法
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值