Created
June 16, 2019 09:57
-
-
Save BitAndQuark/00e9c2dfb849402f51ddcf2a6fb20ee6 to your computer and use it in GitHub Desktop.
CSAPP: Use memory mapping to copy any file on disk to stdout.
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
// 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