Skip to content

Instantly share code, notes, and snippets.

@jdmichaud
Last active August 1, 2018 14:09
Show Gist options
  • Save jdmichaud/74e4491e54d93f85ed51418844b1e5d8 to your computer and use it in GitHub Desktop.
Save jdmichaud/74e4491e54d93f85ed51418844b1e5d8 to your computer and use it in GitHub Desktop.
Load a whole file in C with mmap
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char **argv) {
char *filepath = argv[1];
int fd = open(filepath, O_RDONLY);
if (fd < 0) {
perror("open");
exit(1);
}
off_t size = lseek(fd, 0, SEEK_END);
if (size < 0) {
perror("lseek");
exit(1);
}
char *content = NULL;
content = mmap(content, size, PROT_READ, MAP_SHARED, fd, 0);
fprintf(stdout, "%s", content);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment