linux系统编程:用truncate调整文件大小
2018-01-11 16:44
369 查看
truncate的使用非常简单:
int truncate(const char *path, off_t length);
参数1:文件名
参数2: 文件需要被调整的大小
length 大于 文件大小, 文件后面会填充空白字节或者空洞
length 小于 文件大小, 文件多出的部分,会被舍弃
源代码:
View Code
完整的测试:
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
相关文章推荐
- Linux下对LVM逻辑卷分区大小的调整(针对xfs和ext4不同文件系统)
- Linux下对lvm逻辑卷分区大小的调整(针对xfs和ext4不同文件系统)
- Linux下对lvm逻辑卷分区大小的调整(针对xfs和ext4不同文件系统)
- 系统编程中的文件大小修改truncate/lseek
- 系统编程中的文件大小修改truncate/lseek
- Linux下对LVM逻辑卷分区大小的调整(针对xfs和ext4不同文件系统)
- linux文件系统调整大小的方法(linux调整分区大小)
- Linux中对lvm逻辑卷分区大小的调整教程(针对xfs与ext4不同文件系统)
- Linux下动态调整LVM文件系统大小
- Linux 文件系统大小调整
- Linux下的C编程实战(二)――文件系统编程
- AIX下调整文件系统大小
- Linux 内核编程之文件系统(二)
- Linux文件编程之【系统调用】——close()
- Linux文件编程之【系统调用】——creat()
- Linux文件编程之【系统调用】——write()
- Linux 内核编程之文件系统(二)
- Linux文件编程之【系统调用】——open()
- Linux文件编程之【系统调用】—— lseek()
- Linux 内核编程之文件系统(一)