Linux system programming: Use truncate to adjust the file size, linuxtruncate
The use of truncate is very simple:
Int truncate (const char * path, off_t length );
Parameter 1: File Name
Parameter 2: size of the file to be adjusted
The length is greater than the file size. The file is followed by blank bytes or holes.
The length is smaller than the file size. the excess part of the file will be discarded.
Source code:
1/* ============================================== =========================================== 2 * Copyright (C) 2018. all rights reserved. 3*4 * file name: trunc. c 5 * Creator: ghostwu (Wu Hua) 6 * creation Date: July 7 * description: adjust the file size by 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 ("sets the file size, which must start with 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 ("parameter conversion failed \ n"); 34 exit (-1); 35} 36 37 truncate (argv [1], len); 38 39 return 0; 40}View Code
Complete test:
Ghostwu @ ubuntu :~ /C_program/tlpi/chapter5 $ ls-l test.txt-rw-r -- 1 ghostwu 410 January 11 16:09 test.txt ghostwu @ ubuntu :~ /C_program/tlpi/chapter5 $./trunc test.txt s500ghostwu @ ubuntu :~ /C_program/tlpi/chapter5 $ ls-l test.txt-rw-r -- 1 ghostwu 500 January 11 16:38 test.txt ghostwu @ ubuntu :~ /C_program/tlpi/chapter5 $ vim test.txt ghostwu @ ubuntu :~ /C_program/tlpi/chapter5 $./trunc test.txt 300 set the file size. It must start with "s" and start with ghostwu @ ubuntu :~ /C_program/tlpi/chapter5 $./trunc test.txt s300ghostwu @ ubuntu :~ /C_program/tlpi/chapter5 $ ls-l test.txt-rw-r -- 1 ghostwu 300 January 11 16:38 test.txt