Skip to content

Instantly share code, notes, and snippets.

@BitAndQuark
Created June 16, 2019 09:57
Show Gist options
  • Save BitAndQuark/00e9c2dfb849402f51ddcf2a6fb20ee6 to your computer and use it in GitHub Desktop.
Save BitAndQuark/00e9c2dfb849402f51ddcf2a6fb20ee6 to your computer and use it in GitHub Desktop.
CSAPP: Use memory mapping to copy any file on disk to stdout.
// Use memory mapping to copy any file on disk to stdout.
#include <unistd.h>
#include <sys/mman.h>
#include <stdio.h>
#include <fcntl.h>
int main(int argc, char **argv) {
long sz;
// Open file.
FILE * fp = fopen(argv[1], "r");
// Get file size.
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
fseek(fp, 0L, SEEK_SET);
fclose(fp);
// Map memory.
int fd = open(argv[1], O_RDONLY);
char *bufp = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
// Print.
write(1, bufp, sz);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment