Sparse files are typically handled transparently to the user. But the differences between a normal file and sparse file become apparent in some situations.
Creation The
Unix command dd of=sparse-file bs=5M seek=1 count=0 will create a file of five
mebibytes in size, but with no data stored on the media (only
metadata). (
GNU dd has this behavior because it calls ftruncate to set the file size; other implementations may merely create an empty file.) Similarly the truncate command may be used, if available: truncate -s 5M On
Linux, an existing file can be converted to sparse by: fallocate -d There is no portable system call to punch holes; Linux provides fallocate(FALLOC_FL_PUNCH_HOLE), and
Solaris provides fcntl(F_FREESP).
Detection The -s option of the ls command shows the occupied space in blocks. ls -ls sparse-file Alternatively, the du command prints the occupied space, while ls prints the apparent size. In some non-standard versions of du, the option prints the occupied space in bytes instead of blocks, so that it can be compared to the ls output: du --block-size=1 sparse-file ls -l sparse-file Note the above du usage has the abbreviated option syntax format "du -B 1 sf", itself equivalent to the shortest version "du -b sf" as stated in the du manual: is equivalent to . Also, the tool filefrag from e2fsprogs package can be used to show block allocation details of the file. filefrag -v sparse-file
Copying Normally, the GNU version of
cp is good at detecting whether a file is sparse, so cp sparse-file new-file creates new-file, which will be sparse. GNU also has a --sparse option, which is especially useful if a file containing long zero blocks is saved in a non-sparse way (i.e. the zero blocks have been written to the storage media in full). Storage space can be conserved by doing: cp --sparse=always file1 file1_sparsed Some cp implementations, like
FreeBSD's cp, do not support the --sparse option and will always expand sparse files. A partially viable alternative on those systems is to use
rsync with its own --sparse option instead of cp. Unfortunately, older versions of rsync do not support --sparse combined with --inplace. Via
standard input, sparse file copying is achieved as follows: cp --sparse=always /dev/fd/0 new-sparse-file == See also ==