hpsMouse
hpsMouse

Reputation: 2004

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.

Upvotes: 5

Views: 2586

Answers (4)

MvG
MvG

Reputation: 60868

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.

Upvotes: 6

erk
erk

Reputation: 1

Write zeroes to the portions you don't want.

Upvotes: -2

Christopher
Christopher

Reputation:

The only thing you can do is call ftruncate(), to remove blocks at the end of the file.

Upvotes: 2

Bombe
Bombe

Reputation: 83850

Filesystems only allocate blocks for those parts of the sparse file that do in fact have any content. Removing those blocks would be pretty stupid because that’s your data. The other blocks can not be removed because they do not exist.

Upvotes: 0

Related Questions