文件的截取

在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命令的功能为查看文件的内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值