我想创建一个稀疏文件,这样全零 block 在我向它们写入数据之前不会占用实际磁盘空间。可能吗?
最佳答案
对于默认的 Mac OS X 文件系统 (HFS+) 是否支持文件中的漏洞,似乎存在一些混淆。以下程序证明情况并非如此。
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
void create_file_with_hole(void)
{
int fd = open("file.hole", O_WRONLY|O_TRUNC|O_CREAT, 0600);
write(fd, "Hello", 5);
lseek(fd, 99988, SEEK_CUR); // Make a hole
write(fd, "Goodbye", 7);
close(fd);
}
void create_file_without_hole(void)
{
int fd = open("file.nohole", O_WRONLY|O_TRUNC|O_CREAT, 0600);
write(fd, "Hello", 5);
char buf[99988];
memset(buf, 'a', 99988);
write(fd, buf, 99988); // Write lots of bytes
write(fd, "Goodbye", 7);
close(fd);
}
int main()
{
create_file_with_hole();
create_file_without_hole();
return 0;
}
程序创建了两个文件,每个文件的长度为 100,000 字节,其中一个有一个 99,988 字节的空洞。
在 HFS+ 分区上的 Mac OS X 10.5 上,两个文件占用相同数量的磁盘 block (200):
$ ls -ls
total 400
200 -rw------- 1 user staff 100000 Oct 10 13:48 file.hole
200 -rw------- 1 user staff 100000 Oct 10 13:48 file.nohole
而在 CentOS 5 上,没有漏洞的文件比另一个文件多消耗 88 个磁盘 block :
$ ls -ls
total 136
24 -rw------- 1 user nobody 100000 Oct 10 13:46 file.hole
112 -rw------- 1 user nobody 100000 Oct 10 13:46 file.nohole
关于c - 如何在 Mac OS X 上以 C 语言编程方式创建稀疏文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/186077/