以下的做法整理自论坛上的帖子。
如何create大文件
要大就非常大,1T吧。
有两种方法:
一.dd
dd if=/dev/zero of=1T.img bs=1G seek=1024 count=0
bs=1G表示每一次读写1G数据,count=0表示读写0次,seek=1024表示略过1024个Block不写,前面block size是1G,所以共略过1T!
这是创建大型sparse文件最简单的方法。
二.ftruncate64/ftruncate
如果用系统函数就稍微有些麻烦,因为涉及到宏的问题。我会结合一个实际例子详细说明,其中OPTION标志的就是测试项。
文件sparse.c:
//OPTION 1:是否定义与大文件相关的宏
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64
#include
#include
#include
#include
#include
#include
#define FILENAME "bigfile"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int main(int argc, char **argv)
{
int fd, ret;
off_t offset;
int total = 0;
if ( argc >= 2 )
{
total = atol(argv[1]);
printf("total=%d\n", total);
}
//OPTION 2:是否有O_LARGEFILE选项
//fd = open(FILENAME, O_RDWR|O_CREAT|O_LARGEFILE, 0644);
fd = open(FILENAME, O_RDWR|O_CREAT, 0644);
if (fd < 0) {
perror(FILENAME);
return -1;
}
offset = (off_t)total *1024ll*1024ll*1024ll;
printf("offset=%ld\n", offset);
//OPTION 3:是否调用64位系统函数
//if (ftruncate64(fd, offset) < 0)
if (ftruncate(fd, offset) < 0)
{
printf("[%d]-ftruncate64 error: %s\n", errno, strerror(errno));
close(fd);
return 0;
}
close(fd);
printf("OK\n");
return 0;
}
测试环境:
linux:/disk/test/big # gcc --version
gcc (GCC) 3.3.5 0117 (prerelease) (SUSE Linux)
linux:/disk/test/big # uname -a
Linux linux 2.6.11.4-20a-default #1 Wed Mar 23 21:52:37 UTC i686 i686 i386 GNU/Linux
测试结果