1

I want to preallocate storage with the system call fcntl. Here is my code to do so:

fstore_t store = {F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, length, 0};
int ret = fcntl(fd, F_PREALLOCATE, &store);
if (ret == -1) {
    store.fst_flags = F_ALLOCATEALL;
    ret = fcntl(fd, F_PREALLOCATE, &store);
}

The variable ret is not -1 after executing that code. When I get the file size by calling fstat on the same file handle, I get stat.st_size = 0. But the value store.fst_bytesalloc equals the value of length.
What do I have to do? When I call

ftruncate(fd, length);

do I get a file with a hole or is it a 'real' file without holes? The second one is my goal.

1 Answer 1

3

If your goal is a contiguous space only you should should call fcntl with F_ALLOCATECONTIG flag and fail if ret == -1.

The second call to fcntl in your code (without F_ALLOCATECONTIG flag set) will try to preallocate non-contiguous space (as contiguous allocation failed).

ftruncate call is needed on darwin to have file size reported correctly. Without the call space is being reserved, but file size reported is still zero. Read this article that states that:

It appears that the posix_fallocate equivalent [on OS X] is to the fnctl followed by a truncate() call (which actually forces data to be written to the file)

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! Does this code work as expected with every file system, e.g. ext4 where sparse files are supported? So do I get on those file systems also a file without holes?
This should work with OS X native file systems. Non-native file systems support probably depends on third party tools, like fuse for ext4.
From the fcntl man page, F_ALLOCATECONTIG is not a cmd for fcntl.
@Karl The man page says: "The flags (fst_flags) for the F_PREALLOCATE command are as follows: F_ALLOCATECONTIG Allocate contiguous space. ..."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.