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

相关文章:

  • 2022-12-23
  • 2021-10-16
  • 2021-07-02
  • 2022-12-23
  • 2021-08-11
  • 2022-02-22
  • 2022-01-09
  • 2021-12-30
猜你喜欢
  • 2022-12-23
  • 2021-07-11
  • 2021-08-08
  • 2022-02-07
  • 2022-12-23
  • 2022-01-24
  • 2021-11-08
相关资源
相似解决方案