Conceptadvanced
Sparse file
Also called hole, file hole, sparse data set, apparent size, allocated size, SEEK_HOLE, SEEK_DATA, punch a hole, st_blocks.
A sparse file has holes: ranges that read as zero bytes but have no blocks on the disk. So its size and the space it uses differ, and a copy that reads and writes the zeros fills the holes.
- Applies to
- core-languages
Idea
A file has a size, and it has blocks on the disk that hold its bytes. In most files the two agree. A sparse file has ranges, called holes, that read as zero bytes but have no blocks. A program makes a hole when it moves the file offset past the end of the file and writes there, or when it makes the file longer without writing. So a file of 64 MiB can use only one block of the disk.
import os
import tempfile
os.chdir(tempfile.mkdtemp())
MiB = 1024 * 1024
with open("sparse.bin", "wb") as f:
f.seek(64 * MiB) # move past the end; nothing is written yet
f.write(b"end") # this write leaves a hole of 64 MiB before it
st = os.stat("sparse.bin")
print("size: ", st.st_size)
print("uses less space:", st.st_blocks * 512 < st.st_size)
with open("sparse.bin", "rb") as f:
data = f.read()
print("hole reads as: ", data[:4], "zero bytes:", data.count(0))
fd = os.open("sparse.bin", os.O_RDONLY)
print("first data at: ", os.lseek(fd, 0, os.SEEK_DATA))
print("next hole at: ", os.lseek(fd, 64 * MiB, os.SEEK_HOLE))
os.close(fd)
size: 67108867
uses less space: True
hole reads as: b'\x00\x00\x00\x00' zero bytes: 67108864
first data at: 67108864
next hole at: 67108867
The file has a size of 67108867 bytes, but it uses less space than that, because the first 64 MiB are a hole. A read of the hole gives zero bytes, the same as a read of zeros that were written. SEEK_DATA finds the first byte of data, and SEEK_HOLE after the data gives the end of the file, because each file has a hole at its end.
How it works
Make a hole. POSIX lets the offset go past the end: "The lseek () function shall allow the file offset to be set beyond the end of the existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap"1. The seek alone does not change the size: "The lseek () function shall not, by itself, extend the size of a file"1. ftruncate can also make a file longer: "If the file size is increased, the extended area shall appear as if it were zero-filled"3. Linux calls the gap a hole: "subsequent reads of the data in the gap (a "hole") return null bytes ('\0') until data is actually written into the gap"2.
The standards say what a read gives, not what the disk holds. A file system with holes does not give blocks to the gap. Linux also has a call that removes blocks from a file that has them: with FALLOC_FL_PUNCH_HOLE, fallocate "deallocates space (i.e., creates a hole) in the byte range starting at offset and continuing for size bytes"6. Then "partial filesystem blocks are zeroed, and whole filesystem blocks are removed from the file"6, and the size does not change. Wikipedia notes: "There is no portable system call to punch holes"20.
Two sizes. st_size is the size that a read sees, and st_blocks is the "Number of blocks allocated for this object"4. The unit of st_blocks "is not defined within POSIX.1-2024. In some implementations it is 512 bytes. It may differ on a file system basis"4. Linux warns: "Use of the st_blocks and st_blksize fields may be less portable"5. Python documents it as the "Number of 512-byte blocks allocated for file. This may be smaller than st_size /512 when the file has holes"12. The du command shows the space, and its --apparent-size option will "print apparent sizes rather than device usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, etc."7.
Find the holes. POSIX.1-2024 added two values of whence1. "If whence is SEEK_HOLE, the file offset shall be set to the smallest location of a byte within a hole and not less than offset"1, and "If whence is SEEK_DATA, the file offset shall be set to the smallest location of a byte not within a hole and not less than offset"1. Each file has a hole at its end: "all seekable files shall have a virtual hole starting at the current size of the file, whether or not the file is sparse"1. When the offset is in the hole at the end, SEEK_DATA fails with ENXIO1.
These calls are a hint, not a map of the disk. POSIX says that "Not all bytes with the value zero need belong to a hole"1, and Linux says that "a filesystem is not obliged to report holes, so these operations are not a guaranteed mechanism for mapping the storage space actually allocated to a file"2. A file system can report the whole file as data and give a correct answer.
Copy a sparse file. A plain copy reads each byte and writes it. It reads zeros from a hole and writes them as data, so the copy has no holes. A copy that knows about holes asks for each run of data and writes only that.
import os
import tempfile
os.chdir(tempfile.mkdtemp())
MiB = 1024 * 1024
with open("sparse.bin", "wb") as f:
f.write(b"head")
f.seek(64 * MiB) # leave a hole of about 64 MiB
f.write(b"tail")
def allocated(path):
return os.stat(path).st_blocks * 512 # st_blocks counts 512-byte units
# A plain copy reads the zeros of the hole and writes them as data.
with open("sparse.bin", "rb") as src, open("plain.bin", "wb") as dst:
dst.write(src.read())
# A copy that knows about holes asks for each run of data and skips the holes.
src = os.open("sparse.bin", os.O_RDONLY)
dst = os.open("holes.bin", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
size = os.fstat(src).st_size
pos = 0
while pos < size:
try:
start = os.lseek(src, pos, os.SEEK_DATA)
except OSError: # ENXIO: only a hole is left
break
end = os.lseek(src, start, os.SEEK_HOLE)
os.lseek(src, start, os.SEEK_SET)
os.lseek(dst, start, os.SEEK_SET)
os.write(dst, os.read(src, end - start))
pos = end
os.ftruncate(dst, size) # keep a hole at the end, if there is one
os.close(src)
os.close(dst)
same = open("plain.bin", "rb").read() == open("holes.bin", "rb").read()
print("same bytes: ", same)
print("plain is sparse: ", allocated("plain.bin") < os.path.getsize("plain.bin"))
print("holes is sparse: ", allocated("holes.bin") < os.path.getsize("holes.bin"))
same bytes: True
plain is sparse: False
holes is sparse: True
The two copies have the same bytes, but only the second one has holes. The last ftruncate sets the size, so a hole at the end of the source stays a hole. The tools do the same work. For GNU cp, "By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well"8, and "Specify --sparse = always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes"8. The rsync option --sparse will "Try to handle sparse files efficiently so they take up less space on the destination"9.
Windows. NTFS has sparse files, but a program must ask for them. "When sparse file functionality is enabled, the system does not allocate hard disk drive space to a file except in regions where it contains nonzero data"10. The control code FSCTL_SET_SPARSE "Marks the indicated file as sparse or not sparse"11. For a read, "the file system returns the appropriate number of zeros in the buffer allocated for the read operation"10.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | The os module has lseek, ftruncate, st_blocks and the SEEK_DATA and SEEK_HOLE constants, and the two run blocks of this page use them. No example file exists, because the blocks show the Python calls. |
| C++ | Standard library | |
| Java | Standard library | |
| C | Library | |
| C# | Standard library | FileStream.SetLength makes a file longer and Seek moves past the end. The .NET docs say that on Windows the contents of the new area are undefined, and a program marks a file sparse with FSCTL_SET_SPARSE through DeviceIoControl. .NET has no call for the allocated size. No example file exists. |
| JavaScript | Standard library | |
| TypeScript | Standard library | TypeScript on Node.js uses the node:fs module, with the types from @types/node, so a write at a position, ftruncate and stats.blocks are the same as in the JavaScript example. No example file exists. |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Standard library | Kotlin on the JVM uses java.nio, so a write at a position of a FileChannel and the SPARSE option of the Java example do the work. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | SQL works on tables in a database. The engine chooses the layout of its files, and a query does not make holes. |
| Bash | Native | The truncate -s and dd seek= commands make a hole, du --apparent-size shows the size and du shows the space, and cp --sparse=always copies with holes. No example file exists. |
| PowerShell | Native | The fsutil sparse command marks a file sparse on NTFS, and the .NET calls of FileStream do the rest. No example file exists because pwsh is not installed. |
| HTML | Does not apply | A web page cannot write a file in the local file system. |
| CSS | Does not apply | CSS gives style rules to a document. It does not write files. |
| Regular expressions | Does not apply | A regular expression matches text. It does not write files. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | seek past the end, os.truncate; os.lseek with os.SEEK_DATA and os.SEEK_HOLE; st_blocks of os.stat |
| JavaScript | stdlib | Node.js fs.ftruncateSync or a write at a position; stats.blocks of fs.statSync |
| TypeScript | stdlib | the node:fs module of Node.js, with the types of @types/node |
| Java | stdlib | StandardOpenOption.SPARSE as a hint; a write at a position of a FileChannel; no call for the allocated size |
| Kotlin | stdlib | the java.nio calls of the JVM |
| C# | stdlib | FileStream.SetLength and Seek; on Windows, FSCTL_SET_SPARSE through DeviceIoControl |
| Go | stdlib | File.Seek and File.Truncate; Blocks of syscall.Stat_t on Unix |
| Rust | stdlib | File::set_len; MetadataExt::blocks on Unix |
| C | library | ISO C has no holes; POSIX lseek, ftruncate, SEEK_DATA and SEEK_HOLE, st_blocks |
| C++ | stdlib | std::filesystem::resize_file; the POSIX calls for the holes |
| Bash | native | truncate -s, dd with seek, du --apparent-size, cp --sparse |
| PowerShell | native | fsutil sparse and the .NET calls |
| SQL | n/a | a database stores rows, and the engine chooses the layout of its files |
| Regex | n/a | a pattern matches text and does not write files |
| HTML | n/a | a page does not write files |
| CSS | n/a | style rules do not write files |
Each language with files can make a hole, because a seek past the end and a longer size are ordinary calls. The C++ notes say: "On systems that support sparse files, increasing the file size does not increase the space it occupies on the file system: space allocation takes place only when non-zero bytes are written to the file"19. Rust's set_len "Truncates or extends the underlying file, updating the size of this file to become size"18, and Go's Truncate "changes the size of the file. It does not change the I/O offset"16.
The allocated size is less portable. Rust has blocks only on Unix, and it "Returns the number of blocks allocated to the file, in 512-byte units. Please note that this may be smaller than st_size / 512 when the file has holes"17. Node.js has stats.blocks, "The number of blocks allocated for this file"13. Java has no call for it. Its SPARSE option is a hint: "When used with the CREATE_NEW option then this option provides a hint that the new file will be sparse. The option is ignored when the file system does not support the creation of sparse files"14. In .NET, a longer size is not always zeros: "If the stream is expanded, the contents of the stream between the old and the new length are undefined on Windows, while on Linux, that space is filled with zeros"15.
The example files show a hole in Go, Rust, C, C++, Node.js and Java.
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sys/stat.h>
namespace fs = std::filesystem;
int main() {
fs::path dir = fs::temp_directory_path() / "sparse-cpp-example";
fs::create_directories(dir);
fs::path file = dir / "sparse.bin";
std::ofstream(file) << "head";
// A larger size with no write: the new area reads as zeros.
fs::resize_file(file, 128 * 1024 * 1024);
std::cout << "file_size: " << fs::file_size(file) << '\n';
// std::filesystem has no allocated size, so the example asks POSIX stat.
struct stat st {};
stat(file.c_str(), &st);
std::cout << "uses less space: " << std::boolalpha
<< (static_cast<long long>(st.st_blocks) * 512 < static_cast<long long>(st.st_size)) << '\n';
std::ifstream in(file, std::ios::binary);
in.seekg(64 * 1024 * 1024);
std::cout << "byte at 64 MiB: " << in.get() << '\n';
in.close();
fs::remove_all(dir);
}
file_size: 134217728
uses less space: true
byte at 64 MiB: 0
- Verdict: stdlib.
std::filesystem::resize_filemakes a file longer, and the new area reads as zeros. The library has no call for the allocated size or forSEEK_DATAandSEEK_HOLE, so a program uses the POSIX calls.
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class Main {
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("sparse");
Path file = dir.resolve("sparse.bin");
// SPARSE is a hint for CREATE_NEW. A file system without holes ignores it.
try (FileChannel ch = FileChannel.open(file, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE, StandardOpenOption.SPARSE)) {
ch.write(ByteBuffer.wrap("end".getBytes(StandardCharsets.US_ASCII)), 64 << 20);
}
byte[] data = Files.readAllBytes(file);
System.out.println("size: " + Files.size(file));
System.out.println("first byte: " + data[0]);
System.out.println("last bytes: " + new String(data, data.length - 3, 3, StandardCharsets.US_ASCII));
Files.delete(file);
Files.delete(dir);
}
}
size: 67108867
first byte: 0
last bytes: end
- Verdict: stdlib. A write at a position of a
FileChannelpast the end leaves a hole, andStandardOpenOption.SPARSEis only a hint for a new file. Java has no call that gives the allocated size of a file, and noSEEK_DATAorSEEK_HOLE.
#define _GNU_SOURCE /* SEEK_DATA and SEEK_HOLE on glibc */
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void) {
char path[] = "/tmp/sparse-XXXXXX";
int fd = mkstemp(path);
if (fd < 0) {
perror("mkstemp");
return 1;
}
const off_t mib = 1024 * 1024;
/* Data at 64 MiB, then a size of 128 MiB: a hole, data, and a hole at the end. */
if (pwrite(fd, "data", 4, 64 * mib) != 4 || ftruncate(fd, 128 * mib) != 0) {
perror("write");
return 1;
}
struct stat st;
fstat(fd, &st);
printf("size: %lld\n", (long long)st.st_size);
printf("uses less space: %s\n", (long long)st.st_blocks * 512 < (long long)st.st_size ? "yes" : "no");
off_t data = lseek(fd, 0, SEEK_DATA);
off_t hole = lseek(fd, data, SEEK_HOLE);
printf("data at: %lld\n", (long long)data);
printf("data ends before %s 65 MiB\n", hole <= 65 * mib ? "or at" : "after");
/* The offset is in the hole at the end, so no data follows it. */
errno = 0;
off_t none = lseek(fd, 96 * mib, SEEK_DATA);
printf("after 96 MiB: %lld, %s\n", (long long)none, errno == ENXIO ? "ENXIO" : strerror(errno));
close(fd);
unlink(path);
return 0;
}
size: 134217728
uses less space: yes
data at: 67108864
data ends before or at 65 MiB
after 96 MiB: -1, ENXIO
- Verdict: library. ISO C has no holes. POSIX
lseekpast the end,pwriteandftruncatemake them, andSEEK_DATAandSEEK_HOLEfind them. A file system can round a run of data to its block size, so the example checks only that the data ends before 65 MiB. On glibc, the two constants need_GNU_SOURCE.
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "sparse-"));
const file = path.join(dir, "sparse.bin");
const fd = fs.openSync(file, "w");
// A write at a position past the end leaves a hole before it.
fs.writeSync(fd, Buffer.from("end"), 0, 3, 64 * 1024 * 1024);
fs.closeSync(fd);
const st = fs.statSync(file);
console.log("size: ", st.size);
// stats.blocks counts 512-byte units on POSIX systems.
console.log("uses less space:", st.blocks * 512 < st.size);
const data = fs.readFileSync(file);
console.log("first byte: ", data[0]);
console.log("last bytes: ", data.subarray(-3).toString());
fs.rmSync(dir, { recursive: true });
size: 67108867
uses less space: true
first byte: 0
last bytes: end
- Verdict: stdlib. The
positionargument offs.writeSyncwrites past the end of the file, andfs.ftruncateSyncmakes a file longer.stats.blocksgives the allocated space. Node.js has noSEEK_DATAorSEEK_HOLE.
package main
import (
"fmt"
"io"
"os"
"syscall"
)
// allocated gives the space of the file on the disk. Blocks counts 512-byte units.
func allocated(path string) int64 {
info, err := os.Stat(path)
if err != nil {
panic(err)
}
return info.Sys().(*syscall.Stat_t).Blocks * 512
}
func main() {
dir, err := os.MkdirTemp("", "sparse")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
path := dir + "/sparse.bin"
f, err := os.Create(path)
if err != nil {
panic(err)
}
// A seek past the end and a write leave a hole before the data.
if _, err := f.Seek(64<<20, io.SeekStart); err != nil {
panic(err)
}
if _, err := f.Write([]byte("end")); err != nil {
panic(err)
}
// Truncate to a larger size adds a hole at the end.
if err := f.Truncate(128 << 20); err != nil {
panic(err)
}
f.Close()
info, _ := os.Stat(path)
fmt.Println("size: ", info.Size())
fmt.Println("uses less space:", allocated(path) < info.Size())
data, _ := os.ReadFile(path)
fmt.Printf("bytes 0..3: %q\n", data[:3])
fmt.Printf("bytes at 64 MiB: %q\n", data[64<<20:64<<20+3])
}
size: 134217728
uses less space: true
bytes 0..3: "\x00\x00\x00"
bytes at 64 MiB: "end"
- Verdict: stdlib.
File.Seekpast the end andFile.Truncateto a larger size make holes. The allocated size is not infs.FileInfo, so the example readsBlocksfromsyscall.Stat_t, which exists only on Unix.SEEK_DATAandSEEK_HOLEare not constants of theiopackage.
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::os::unix::fs::MetadataExt;
fn main() -> std::io::Result<()> {
let dir = std::env::temp_dir().join(format!("sparse-{}", std::process::id()));
fs::create_dir_all(&dir)?;
let path = dir.join("sparse.bin");
let mut f = OpenOptions::new().write(true).create(true).truncate(true).open(&path)?;
f.set_len(128 << 20)?; // a larger size with no write: the file is one hole
f.seek(SeekFrom::Start(64 << 20))?;
f.write_all(b"mid")?; // data in the middle of the hole
drop(f);
let meta = fs::metadata(&path)?;
println!("len: {}", meta.len());
// blocks() counts 512-byte units, on Unix only.
println!("uses less space: {}", meta.blocks() * 512 < meta.len());
let mut f = File::open(&path)?;
let mut head = [1u8; 4];
f.read_exact(&mut head)?;
println!("hole reads as: {:?}", head);
let mut mid = [0u8; 3];
f.seek(SeekFrom::Start(64 << 20))?;
f.read_exact(&mut mid)?;
println!("at 64 MiB: {:?}", std::str::from_utf8(&mid).unwrap());
fs::remove_dir_all(&dir)
}
len: 134217728
uses less space: true
hole reads as: [0, 0, 0, 0]
at 64 MiB: "mid"
- Verdict: stdlib.
File::set_lenmakes a file longer without a write, and a seek past the data and a write make a hole.MetadataExt::blocksgives the allocated space, but only on Unix. The standard library has no call forSEEK_DATAorSEEK_HOLE.
Variations and related ideas
- Punch a hole. On Linux,
fallocatewithFALLOC_FL_PUNCH_HOLEremoves the blocks of a range in a file that has them, and the range then reads as zeros6. - Preallocate. This is the opposite of a hole.
fallocatewith no flags gives blocks to a range before a program writes it, and then "subsequent writes into the range specified by offset and size are guaranteed not to fail because of lack of disk space"6. POSIX hasposix_fallocatefor the same work6. - Disk images and databases. Wikipedia says: "Sparse files are commonly used for disk images , database snapshots , log files and in scientific applications"20. A virtual disk of a fixed size uses space only for the blocks that the guest writes.
- Copy and size. A copy can keep or lose the holes, and the size of a file has two meanings. See Copy a file and Get the size of a file.
Pitfalls
- A copy fills the holes. A program that reads a file and writes the bytes makes a copy with no holes, as the second example shows. A file of 1 GiB with 1 MiB of data becomes 1 GiB on the disk. Use a copy that knows about holes, such as
cporrsync --sparse9. - A write into a hole can fail for lack of space. A hole has no blocks, so a write there needs new blocks. Wikipedia lists "disk-full or quota-exceeded errors when merely overwriting an existing portion of a file that happened to have been sparse"20. A program that must not fail later can preallocate the space6.
- The size is not the space.
st_size,lsand the size calls of each language give the apparent size. Usest_blocksordufor the space, and do not use the apparent size to plan the free space of a disk7. - The unit of st_blocks varies. POSIX does not define it4. Linux and Python use 512 bytes12, which is not the block size of the file system.
- Holes are not portable. Some file systems have no holes, and an archive or a network copy can lose them. A program must give the same result when the file has no holes, and use holes only to save space.
Cost
A hole costs no blocks, only the metadata that marks it. A read of a hole gives zeros with no read of the disk. A write into a hole allocates blocks, so the file can become fragmented: Wikipedia says that "sparse files may become fragmented"20. A copy that uses SEEK_DATA and SEEK_HOLE does work for each run of data, not for each byte, so it is fast on a file with large holes.
History
POSIX lets a program seek past the end of a file and write there, and it requires a read of the gap to give zeros1. The Wikipedia article on sparse files cites a change by Jim Meyering on 1995-12-21 that gave GNU cp its --sparse option, and a change by Andrew Tridgell on 1996-06-29 with "better sparse handling" in rsync20. POSIX added SEEK_HOLE and SEEK_DATA in Issue 8: "Austin Group Defect 415 is applied, adding SEEK_HOLE and SEEK_DATA"1. NTFS has sparse files that a program turns on with FSCTL_SET_SPARSE1011.
References
- The Open Group, POSIX.1-2024, lseek, Description, Errors, Rationale, Change History
- lseek(2), Linux manual page, Description, Seeking file data and holes
- The Open Group, POSIX.1-2024, ftruncate, Description
- The Open Group, POSIX.1-2024, sys/stat.h, Description, Application Usage
- stat(2), Linux manual page, Notes
- fallocate(2), Linux manual page, Description, Deallocating file space
- du(1), Linux manual page, --apparent-size
- cp(1), Linux manual page, --sparse
- rsync(1) manpage, --sparse, -S
- Sparse Files, Win32 apps, Microsoft Learn, Overview
- FSCTL_SET_SPARSE IOCTL (winioctl.h), Win32 apps, Microsoft Learn, Description
- The Python Standard Library, os, os.lseek, os.stat_result.st_blocks
- Node.js, File system, Class fs.Stats, stats.blocks
- Java SE 25 API, java.nio.file.StandardOpenOption, SPARSE
- FileStream.SetLength(Int64) Method (System.IO), .NET API, Microsoft Learn, Remarks
- Go standard library, package os, func (*File) Truncate, func (*File) Seek
- The Rust Standard Library, std::os::unix::fs::MetadataExt, fn blocks
- The Rust Standard Library, std::fs::File, fn set_len
- std::filesystem::resize_file, cppreference.com, Description, Notes
- Sparse file, Wikipedia, Disadvantages, Sparse files in Unix, References
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 771ACQ Edit this page History Report an error Markdown