所谓的截断,就是把一个文件的尾部砍掉。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 12月 1 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 12月 1 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 函数的用法