linux truncate文件,linux系统编程:用truncate调整文件大小
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
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
總結
以上是生活随笔為你收集整理的linux truncate文件,linux系统编程:用truncate调整文件大小的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 生藕汁的功效与作用、禁忌和食用方法
- 下一篇: linux内核分为子系统,Linux内核