Question

Actually, I have two questions.

What fallocate() does?

I read the man page and have the following understanding. For filesystems that support hole in file, fallocate() is used to punch holes and allocate new spaces in the file. For filesystems without holes, fallocate() can only be used to allocate new space after the end of file, i.e., it only has effect when len + offset > file_size.

Is my understanding correct? If so, I also have the following question.

fallocate() vs ftruncate() when extending file

Now I want to create a new file and allocate a specific size of zero-filled bytes in the file. I realized that both fallocate() and ftruncate() can do the job. What's their difference?

BTW, I know that fallocate() is not portable, but since my program is only for Linux, portability to other Unix-like systems is not taken into consideration.

Thank you!

Was it helpful?

Solution

Use posix_fallocate(3) in your code. The difference with ftruncate(2) is that (on file systems supporting it, e.g. Ext4) disk space is indeed reserved by posix_fallocate but ftruncate extends the file by adding holes (and without reserving disk space).

E.g. if you disk is 100Gbytes, and you posix_fallocate a 5Gb file, you'll see (with df) that available space has reduced (since before the call); if you did only an ftruncate you won't see available space reducing.

See also this answer to a related question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top