Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove some blocks from a sparse file on a ext2/ext3 filesystem

The ext2/ext3 filesystem automatically allocate blocks when you write a sparse file, but when I no longer want some blocks of them, I found no ways to do it. It feels like using malloc() without free(). Is it possible to "free" some blocks of a sparse file? If it is, how? Don't tell me to copy it to a new file. It's too boring and needs a lot of disk space.

like image 356
hpsMouse Avatar asked Aug 12 '09 09:08

hpsMouse


People also ask

How does EXT2 file system work?

The EXT2 file system divides the logical partition that it occupies into Block Groups. Each group duplicates information critical to the integrity of the file system as well as holding real files and directories as blocks of information and data.

Does ext4 support sparse files?

That is why sparse files originally take up less space than their real size is. This file type is supported by most file systems: BTRFS, NILFS, ZFS, NTFS[2], ext2, ext3, ext4, XFS, JFS, ReiserFS, Reiser4, UFS, Rock Ridge, UDF, ReFS, APFS, F2FS.

What is a sparse file record?

A file format that saves storage space by recording only actual data. Whereas regular files record empty fields as blank data or runs of nulls, a sparse file includes meta-data that describe where the runs of non-data are located. The reported file size is always the size of the entire file.


1 Answers

Since Linux 2.6.38, there is a flag to fallocate called FALLOC_FL_PUNCH_HOLE which should do what you want, i.e. deallocate file space at arbitrary locations.

fallocate(fd, FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE, offset, len);

will punch a hole into the file indicated by descriptor fd. The hole will start at offset and have length len, both measured in bytes. Only whole blocks will actually be removed, partial blocks will be zeroed out instead.

like image 160
MvG Avatar answered Nov 09 '22 10:11

MvG