What does C – fallocate() do?

What does C – fallocate() do? … here is a solution to the problem.

What does C – fallocate() do?

Actually, I have two questions.

What does fallocate() do?

I read the man page and have the following understanding. For file systems that support file holemaking, fallocate() is used to punch holes and allocate new space in the file. For filesystems without vulnerabilities, fallocate() can only be used to allocate new space after the file ends, i.e. only valid when len + offset > file_size.

Am I understanding correctly? If so, I also have the following questions.

fallocate() vs ftruncate() extension file

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

By the way, I know that fallocate() is not portable, but since my program only works with Linux, it doesn’t take into account portability of other Unix-like systems.

Thanks!

Solution

Use posix_fallocate (3) in your code. The difference with ftruncate(2) is that (on the file system that supports it, e.g. Ext4) disk space is indeed posix_ fallocate reserves, but ftruncate expands the file by adding holes (and not preserving disk space).

For example, if your disk is 100Gbytes and you posix_fallocate a 5Gb file, you will see (using df) that the free space has been reduced (since before the call); If you only do ftruncate, you won’t see a decrease in free space.

See also this answer a related question.

Related Problems and Solutions