linux系统调用 ftruncate设置文件大小

系统调用ftruncate可以将一个文件裁剪为指定的大小,函数描述如下:

  • 头文件:
  • 函数使用:
    int truncate(const char *path, off_t length);
    int ftruncate(int fd, off_t length);
  • 函数参数:
    可以看到两者有不同的使用方式,truncate是通过文件路径来裁剪文件大小,而ftruncate是通过文件描述符进行裁剪;
  • 返回值
    成功:0
    失败:-1
  • 权限要求:
    ftruncate要求文件被打开且拥有可写权限
    truncate要求文件拥有可写权限
  • 注意:
    如果要裁剪的文件大小大于设置的off_t length,文件大于length的数据会被裁剪掉
    如果要裁剪的文件小于设置的offt_t length,则会进行文件的扩展,并且将扩展的部分都设置为\0,文件的偏移地址不会发生变化
    ftruncate主要被用作POSIX共享内存对象的大小设置

函数使用:

#include 
#include 
#include 
#include 
#include 
#include 

#define TRUN "./test_truncate"
int main() {
	char *name = "test_file";
	//打开文件且拥有可写权限
	int fd = open(name,O_CREAT|O_RDWR,0666);
	if ( -1 == fd ) {
		printf("open %s failed \n",name);
		_exit(-1);
	}
	
	//通过文件描述符对文件大小进行裁剪
	if(ftruncate(fd,4096) != -1) {
		printf("ftruncate success \n");
	}
	
	//直接设置指定路径的文件大小
	if(truncate(TRUN,8192) != -1) {
		printf("truncate success\n");
	}

	//通过fstat获取文件属性信息
	struct stat buf;
	fstat(fd,&buf);
	printf("stat.size is %ld \n",buf.st_size);
	printf("stat.inode is %ld \n",buf.st_ino);
	printf("stat.mode is %lo(octal) \n",(unsigned long)buf.st_mode);
	printf("stat.bytes is %ld \n",buf.st_blksize);
	close(fd);
	return 0;
}

你可能感兴趣的:(#,编程语言C,编程语言)