Is there a way to create sparse files from Rust? Here, by Sparse file I mean files where if an entire Page is 0, the OS optimizes it away.
Googling, there are various ways to create such files via truncate or dd. However, I can't find anyway to create one from Rust (googling returns sparse linear algebra libraries).
[Context: for mmapped on-disk b-trees, if we drop an entire page, we don't want it to waste disk space.]
According to this article, you can create a sparse file by using lseek() to move the file's cursor to a particular location and the OS will automatically treat the space in between as empty...
The full patch was declined (issue 58635), but you can see a method of copying sparse files in rust in this PR. There's also the hole-punch crate, which seems unmaintained, but can likely be used as a reference.
Sorry for bumping an old thread, but I was just looking for this and I wanted to confirm that, at least on Linux, using seek and writing a dummy byte seems to work.
For example:
let mut file = File::create("sparse.rs").unwrap();
file.seek(SeekFrom::Start(1140549487)).unwrap();
file.write_all(&[0]).unwrap();
will create a 1.1gb sparse file called sparse.rs in an unwrap-happy way
In linux, you can use the (non-POSIX) fallocate system call -- see the "Deallocating file space" section which talks about the FALLOC_FL_PUNCH_HOLE mode.