5

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.

rahul
  • 184,426
  • 49
  • 232
  • 263
hpsMouse
  • 2,004
  • 15
  • 20

4 Answers4

6

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.

MvG
  • 57,380
  • 22
  • 148
  • 276
  • 1
    So this feature is finally added into Linux kernel. Thank you for answering my 3-year-old question. :D – hpsMouse Sep 09 '12 at 06:51
2

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

0

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.

Bombe
  • 81,643
  • 20
  • 123
  • 127
  • But there really exist situations that I don't want some blocks of a file any more and want to give the space back to the filesystem. – hpsMouse Aug 13 '09 at 02:21
-2

Write zeroes to the portions you don't want.

erk
  • 1
  • 2
    This won't work, the block will now contain zeros instead of the 'hole' the original question is looking for. – Nick Garvey Jun 30 '13 at 21:46