在Linux系统有时会有在文件尾端处截去一些数据以缩短文件的需求。因此为了截短文件可以调用函数truncate()和ftruncate()。
#include <unistd.h>
#include <sys/types.h>
int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);
这两个函数的功能为将路径名path或打开的文件描述符fd所指定的一个现存文件截短为length长度。如果该文件以前的长度大于length,则超过length以外的数据就不再能存取。如果以前的长度短于length,则其后果与系统有关。具体如例1-3所示。
例1-3 truncate.c
1 #include <stdio.h>
2 #include <sys/types.h>
3
4 int main(int argc, const char *argv[])
5 {
6 off_t offset = 12;
7 if(truncate(argv[1], offset) < 0){
8 printf("truncate error\n");
9 return -1;
10 }
11 return 0;
12 }
例1-3的运行结果如下所示。
linux@Master:~/1000phone$ cat test.txt
hello world
hello world
linux@Master:~/1000phone$ ls -l test.txt
-rw-rw-r-- 1 linux linux 24 4月 11 16:30 test.txt
linux@Master:~/1000phone$ ./a.out test.txt
linux@Master:~/1000phone$ ls -l test.txt
-rw-rw-r-- 1 linux linux 12 4月 11 16:32 test.txt
linux@Master:~/1000phone$ cat test.txt
hello world
test.txt文件中原有写入24字节的数据。运行程序,使用命令行传参,将文件test.txt作为参数传递给执行程序,运行之后,文件的大小变为12字节。使用cat命令的功能为查看文件的内容。