Last active
April 11, 2017 05:34
-
-
Save braydonf/059146ac00c8d878bbb1e226ac8aa934 to your computer and use it in GitHub Desktop.
allocate file test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _GNU_SOURCE | |
#ifdef _WIN32 | |
#include <windows.h> | |
#endif | |
#include <errno.h> | |
#include <fcntl.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <string.h> | |
static int allocate_file(int fd, uint64_t length) | |
{ | |
#ifdef _WIN32 | |
HANDLE file = (HANDLE)_get_osfhandle(fd); | |
if (file == INVALID_HANDLE_VALUE) { | |
return EBADF; | |
} | |
int status = 0; | |
LARGE_INTEGER size; | |
size.HighPart = (uint32_t)((length & 0xFFFFFFFF00000000LL) >> 32); | |
size.LowPart = (uint32_t)(length & 0xFFFFFFFFLL); | |
if (!SetFilePointerEx(file, size, 0, FILE_BEGIN)) { | |
status = GetLastError(); | |
goto win_finished; | |
} | |
if (!SetEndOfFile(file)) { | |
status = GetLastError(); | |
goto win_finished; | |
} | |
win_finished: | |
CloseHandle(file); | |
return status; | |
#elif __APPLE__ | |
fstore_t store = {F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, length, 0}; | |
// Try to get a continous chunk of disk space | |
int ret = fcntl(fd, F_PREALLOCATE, &store); | |
if (-1 == ret) { | |
// OK, perhaps we are too fragmented, allocate non-continuous | |
store.fst_flags = F_ALLOCATEALL; | |
ret = fcntl(fd, F_PREALLOCATE, &store); | |
if ( -1 == ret) { | |
return -1; | |
} | |
} | |
return ftruncate(fd, length); | |
#else | |
return fallocate(fd, FALLOC_FL_ZERO_RANGE, 0, length); | |
#endif | |
} | |
int main() | |
{ | |
FILE *fp = fopen("./test.data", "w+"); | |
if (!fp) { | |
printf("Unable to open file: %s\n", strerror(errno)); | |
return 1; | |
} | |
int fd = fileno(fp); | |
allocate_file(fd, 1024 * 10); | |
fclose(fp); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment