快速创建大文件,如10G。文件大小是10G,但创建过程中并不会向文件写入10G数据。因此速度非常快。主要用于制作磁盘/分区映像,大型文件下载。
方法一:Linux命令
##创建完成后,可以将它们进行格式化,并当做文件系统进行挂载。我格式化成ext4之后,可以看到superblock、block group等信息,挂载之后使用df -h可以看到这个分区的大小是:前者10G,后者30G。
##而且这个大文件所在目录的文件系统的空间使用率几乎没有增加(只增加了100+M),我认为这是因为这个文件是空洞文件,虽然分配了一堆block的,但是没有使用,使用的时候将bmap标记为使用之后,空间就会增加了。
fallocate -l 10G bigfile ##创建一个10G的文件(使用ll查看,大小为10G) ##挂在之后看到分区,这个分区是10G
fallocate -l 10G -o 20G bigfile2 ##创建一个10G的文件,偏移量为20G(使用ll查看,大小为30G;通过df -h看到只占用了10G;通过du看到只占用了100+M的空间)
dd of=bigfile bs=1 seek=10G count=0
truncate -s 10G bigfile
方法二:C程序
linux
在Linux中,使用lseek或truncate到一个固定位置生成的“空洞文件”是不会占据真正的磁盘空间的。支持此操作的文件系统:ext4/xfs。
网上的例子:
lseek可以用于快速创建一个大文件。
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<unistd.h>
int main(void)
{
int fd;
char buf1[]="1234567890";
char buf2[]="0987654321";
fd=open("file.hole",O_WRONLY|O_CREAT|O_TRUNC);
if(fd<0)perror("creat file fail");
if(write(fd,buf1,10)==-1)perror("could not write");
if(lseek(fd,1000,SEEK_CUR)==-1)
perror("could not sleek");
if(write(fd,buf2,10)==-1)perror("could not write");
if(lseek(fd,12,SEEK_SET)==-1)perror("could not sleek");
if(write(fd,"abcdefg",7)==-1)perror("could not write");
// fsync
// write content to file
// then fdatasync, fsync
return 0;
}