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 <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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM