From a5c2c35bf6162957a7c7199e439ec1ada145ec92 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Sun, 7 Sep 2025 21:40:33 +0200 Subject: [PATCH] file_allocate --- file_allocate.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 file_allocate.c diff --git a/file_allocate.c b/file_allocate.c new file mode 100644 index 0000000..d1b61c9 --- /dev/null +++ b/file_allocate.c @@ -0,0 +1,67 @@ +#define _GNU_SOURCE /* Required for linux fallocate */ +#include +#include +#include +#include +#include + +int posix_falloc(void); +int file_trunc(void); +int linux_falloc(void); + +#define FILENAME "allocated.bin" + +int main(void) { + posix_falloc(); + file_trunc(); + linux_falloc(); + + return EXIT_SUCCESS; +} + +int posix_falloc(void) { + int fd = open(FILENAME, O_CREAT | O_WRONLY, 0666); + if (fd == -1) { + return EXIT_FAILURE; + } + + off_t length = 1024 * 1024; // 1 MB + int ret = posix_fallocate(fd, 0, length); + if (ret != 0) { + return EXIT_FAILURE; + } + + close(fd); + remove(FILENAME); + return EXIT_SUCCESS; +} + +int linux_falloc(void) { + int fd = open(FILENAME, O_CREAT | O_WRONLY, 0666); + if (fd == -1) { + perror("Error"); + return EXIT_FAILURE; + } + + off_t length = 1024 * 1024; // 1 MB + if (fallocate(fd, 0, 0, length) == -1) { + perror("fallocate"); + return EXIT_FAILURE; + } + + close(fd); + remove(FILENAME); + return EXIT_SUCCESS; +} + +int file_trunc(void) { + int fd = open(FILENAME, O_CREAT | O_WRONLY, 0666); + if (fd == -1) { + perror("Error"); + return EXIT_FAILURE; + } + off_t length = 1024 * 1024; // 1 MB + ftruncate(fd, length); + remove(FILENAME); + return EXIT_SUCCESS; +}