Skip to content

Instantly share code, notes, and snippets.

@jpauli
Created June 13, 2014 14:17
Show Gist options
  • Save jpauli/8afec7c4fc2b38f8ff27 to your computer and use it in GitHub Desktop.
Save jpauli/8afec7c4fc2b38f8ff27 to your computer and use it in GitHub Desktop.
fallocate VS ftruncate demo
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
if (argc != 3) {
printf("Usage: allocate <1:ftruncate, 2:fallocate> <size> \n");
exit(1);
}
char cwd[255], path[255];
if (!getcwd(cwd, sizeof(cwd))) {
perror("Path too large");
exit(1);
}
if (snprintf(path, 255, "%s/__allocate_chunk", cwd) >= 255) {
perror("Path too large");
exit(1);
}
printf("now opening %s\n", path);
int fd;
fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
if (fd == -1) {
perror("Could not open the test file");
exit(1);
}
int size = atoi(argv[2]);
int mode = atoi(argv[1]);
int ret;
switch(mode) {
case 1:
printf("Using ftruncate \n");
ret = ftruncate(fd, size);
break;
case 2:
printf("Using fallocate\n");
ret = posix_fallocate(fd, 0, size);
break;
default:
fprintf(stderr, "Unkown mode : %d", mode);
exit(-1);
}
if (ret) {
perror("error writing");
exit(1);
}
struct stat filestats;
fstat(fd, &filestats);
printf("Done !, st_blocks=%ld\n", filestats.st_blocks);
close(fd);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment