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


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

 

相关内容