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

时间:2023-03-08 19:27:59
linux系统编程:用truncate调整文件大小

truncate的使用非常简单:

int truncate(const char *path, off_t length);

参数1:文件名

参数2:  文件需要被调整的大小

length 大于 文件大小, 文件后面会填充空白字节或者空洞

length 小于 文件大小, 文件多出的部分,会被舍弃

源代码:

 /*================================================================
* Copyright (C) 2018 . All rights reserved.
*
* 文件名称:trunc.c
* 创 建 者:ghostwu(吴华)
* 创建日期:2018年01月11日
* 描 述:调整文件大小
*
================================================================*/ #include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <limits.h> int main(int argc, char *argv[])
{
if( argc < || strcmp( argv[], "--help" ) == ) {
printf( "usage:%s filename s<length>\n", argv[] );
exit( - );
} if( argv[][] != 's' ) {
printf( "设置文件的大小,需要用s开头\n" );
exit( - );
} char* endptr;
long int len = strtol( &argv[][], &endptr, );
if( len == LONG_MIN || len == LONG_MAX ) {
printf( "参数转换失败\n" );
exit( - );
} truncate( argv[], len ); return ;
}

完整的测试:

ghostwu@ubuntu:~/c_program/tlpi/chapter5$ ls -l test.txt
-rw-rw-r-- ghostwu ghostwu 1月 : 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-- ghostwu ghostwu 1月 : test.txt
ghostwu@ubuntu:~/c_program/tlpi/chapter5$ vim test.txt
ghostwu@ubuntu:~/c_program/tlpi/chapter5$ ./trunc test.txt
设置文件的大小,需要用s开头
ghostwu@ubuntu:~/c_program/tlpi/chapter5$ ./trunc test.txt s300
ghostwu@ubuntu:~/c_program/tlpi/chapter5$ ls -l test.txt
-rw-rw-r-- ghostwu ghostwu 1月 : test.txt