您的位置:首页 > 运维架构 > Linux

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

2018-01-11 16:44 369 查看
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 < 3 || strcmp( argv[1], "--help" ) == 0 ) {
printf( "usage:%s filename s<length>\n", argv[0] );
exit( -1 );
}

if( argv[2][0] != 's' ) {
printf( "设置文件的大小,需要用s开头\n" );
exit( -1 );
}

char* endptr;
long int len = strtol( &argv[2][1], &endptr, 10 );
if( len == LONG_MIN || len == LONG_MAX ) {
printf( "参数转换失败\n" );
exit( -1 );
}

truncate( argv[1], len );

return 0;
}


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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: