码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2018-01-11 17:38:07      阅读:379      评论:0      收藏:0      [点我收藏+]

标签:name   转换   copy   参数   大于   str   系统编程   class   ide   

truncate的使用非常简单:

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

参数1:文件名

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

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

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

源代码:

技术分享图片
 1 /*================================================================
 2 *   Copyright (C) 2018 . All rights reserved.
 3 *   
 4 *   文件名称:trunc.c
 5 *   创 建 者:ghostwu(吴华)
 6 *   创建日期:2018年01月11日
 7 *   描    述:调整文件大小
 8 *
 9 ================================================================*/
10 
11 #include <stdio.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <stdlib.h>
15 #include <sys/types.h>
16 #include <limits.h>
17 
18 int main(int argc, char *argv[])
19 {
20     if( argc < 3 || strcmp( argv[1], "--help" ) == 0 ) {
21         printf( "usage:%s filename s<length>\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

 

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

标签:name   转换   copy   参数   大于   str   系统编程   class   ide   

原文地址:https://www.cnblogs.com/ghostwu/p/8269220.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!