linux truncate文件,linux系统编程:用truncate调整文件大小

truncate的使用非常简单:

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

参数1:文件名

参数2:  文件需要被调整的大小

length 大于 文件大小, 文件后面会填充空白字节或者空洞

length 小于 文件大小, 文件多出的部分,会被舍弃

源代码:

f12d4a9165be0c481992f693fe5165bc.png

45d4990ca000170a06f9b53d87e16a39.png

1 /*================================================================

2 * Copyright (C) 2018 . All rights reserved.

3 *

4 * 文件名称:trunc.c

5 * 创 建 者:ghostwu(吴华)

6 * 创建日期:2018年01月11日

7 * 描 述:调整文件大小

8 *

9 ================================================================*/

10

11 #include

12 #include

13 #include

14 #include

15 #include

16 #include

17

18 int main(int argc, char *argv[])

19 {

20 if( argc < 3 || strcmp( argv[1], "--help" ) == 0 ) {

21 printf( "usage:%s filename s\n", argv[0] );

22 exit( -1 );

23 }

24

25 if( argv[2][0] != 's' ) {

26 printf( "设置文件的大小,需要用s开头\n" );

27 exit( -1 );

28 }

29

30 char* endptr;

31 long int len = strtol( &argv[2][1], &endptr, 10 );

32 if( len == LONG_MIN || len == LONG_MAX ) {

33 printf( "参数转换失败\n" );

34 exit( -1 );

35 }

36

37 truncate( argv[1], len );

38

39 return 0;

40 }

View Code

完整的测试:

ghostwu@ubuntu:~/c_program/tlpi/chapter5$ ls -l test.txt

-rw-rw-r-- 1 ghostwu ghostwu 410 1月 11 16:09 test.txt

ghostwu@ubuntu:~/c_program/tlpi/chapter5$ ./trunc test.txt s500

ghostwu@ubuntu:~/c_program/tlpi/chapter5$ ls -l test.txt

-rw-rw-r-- 1 ghostwu ghostwu 500 1月 11 16:38 test.txt

ghostwu@ubuntu:~/c_program/tlpi/chapter5$ vim test.txt

ghostwu@ubuntu:~/c_program/tlpi/chapter5$ ./trunc test.txt 300

设置文件的大小,需要用s开头

ghostwu@ubuntu:~/c_program/tlpi/chapter5$ ./trunc test.txt s300

ghostwu@ubuntu:~/c_program/tlpi/chapter5$ ls -l test.txt

-rw-rw-r-- 1 ghostwu ghostwu 300 1月 11 16:38 test.txt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值