How can I read a file with mmap in C?

Yesterday I introduced mmap as a way to map physical memory into the address space. But mmap is more well-known for its ability to map files into the address space.

Here’s an example of reading the system dictionary file by memory-mapping it.

#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>

int main(void) {
  int fd = open("/usr/share/dict/words", O_RDONLY);
  size_t pagesize = getpagesize();
  char * region = mmap(
    (void*) (pagesize * (1 << 20)), pagesize,
    fd, 0
  fwrite(region, 1, pagesize, stdout);
  int unmap_result = munmap(region, pagesize);
  return 0;
I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged . All content copyright James Fisher 2017. This post is not associated with my employer. Found an error? Edit this page.