Logo Questions Linux Laravel Mysql Ubuntu Git Menu

How to check if a file of given length can be created?







I want to create a non-sparse file of a given length (i.e. 2GB), but I want to check if that is possible before actually writing stuff to disk.

In other words I want to avoid getting ENOSPC (No space left on device) while writing. I'd prefer not to create a "test file" of size 2GB or things like that just to check that there is enough space left.

Is that possible?

like image 606
leonixyz Avatar asked Feb 12 '23 07:02


1 Answers

Use posix_fallocate(3).

From the description:

The function posix_fallocate() ensures that disk space is allocated for the file referred to by the descriptor fd for the bytes in the range starting at offset and continuing for len bytes. After a successful call to posix_fallocate(), subsequent writes to bytes in the specified range are guaranteed not to fail because of lack of disk space

like image 149
D Krueger Avatar answered Feb 13 '23 20:02

D Krueger