A sparse file is a type of computer file that has holes in it. These holes don’t contain actual data. A spare file only allocates disk space for the data that are actually stored.
This allows a sparse file to appear to be much larger than it actually is, while taking up very little space on the disk.
The operating system still stores information about the location and size of these holes so that it can read from and write to them. This reduces the total amount of disk space used while keeping all the data associated with the file intact.
Sparse files is one way to make disk space usage more efficient. 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.
Table of Contents
How to check a sparse file in Linux
To check if a file is sparse, you can use the ls command with the -s flag, which will display the actual size of the file in bytes, rather than the size it appears to be. For example:
ls -s myfile.txt
This will display the actual size of the file myfile.txt in bytes. If the size displayed is much smaller than the file’s apparent size (as shown by the ls command without the -s flag, or by the file’s properties in a GUI file manager), then the file is likely a sparse file.
Alternatively, you can use the du command with the –apparent-size flag to display the apparent size of the file in bytes. For example:
du --apparent-size myfile.txt
This will display the apparent size of the file myfile.txt in bytes. If the size displayed is much larger than the file’s actual size (as shown by the du command with the –apparent-size flag. then the file is likely a sparse file.
Note that some file systems, such as NTFS and ext4, natively support sparse files.
If a file system does not support sparse files, then a file that is created as a sparse file will consume disk space as if it were a regular file, with all of its blocks allocated.
How to create a sparse file in Linux
To create a sparse file in Linux, you can use the truncate command. To create a sparse file of size 2GB for example, you would type the following command.
truncate -s 2G testfile.img
This creates an empty sparse file with no actual content, but the space is allocated on disk so the operating system will recognize it as a valid file. You can then write data to it as needed.
Let us check the file size with ls command.
$ ls -lrht testfile.img
-rw------- 1 ocp ocp 2.0G Dec 24 10:54 testfile.img
The actual size for this file is zero.
$ ls -sh testfile.img
$ du -sh testfile.img