Search code examples
cbinaryfilesmmap

Using memory mapping in C for reading binary


I am trying to read data from a very large binary file and process it using memory mapping, so it can be read byte by byte. I am getting a few compiler errors while doing this, and I can't figure out what is causing them. I am doing this on a linux platform, for the record.

#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include<stdio.h>
#include<stdlib.h>
int fd;
char *data;

fd = open("data.bin", O_RDONLY);
pagesize = 4000;
data = mmap((caddr_t)0, pagesize, PROT_READ, MAP_SHARED, fd, pagesize);

The errors I get are as follows:

caddr not initialized

R_RDONLY not initialized

mmap has too few arguments.

I am using a Makefile to compile it, which looks like this:

all: order_book
CC = gcc 
CFLAGS = -std=c99

order_book: main.c
    $(CC) $(CFLAGS) -o order_book main.c
clean: 
    rm -f order_book

What am I doing wrong, and what can I do to fix it?


Solution

  • Several errors, if this is indeed the entire piece of code that fails:

    1. O_RDONLY requires fcntl.h to be included.
    2. The code is defined outside of any function.
    3. The first argument to mmap is a void *, so just use NULL.
    4. pagesize is not declared.

    The following compiles:

    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/mman.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>
    
    int fd;
    char *data;
    
    void main(int argc, char *argv[]) {
      fd = open("data.bin", O_RDONLY);
      int pagesize = 4000;
      data = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fd, pagesize);
    }