Reading a file to string with mmap

Viewed 34112

I'm trying to read a file to a string using mmap.

I was following this example: http://www.lemoda.net/c/mmap-example/index.html

My code looks like this

unsigned char *f;
int size;
int main(int argc, char const *argv[])
{
    struct stat s;
    const char * file_name = argv[1];
    int fd = open (argv[1], O_RDONLY);

    /* Get the size of the file. */
    int status = fstat (fd, & s);
    size = s.st_size;

    f = (char *) mmap (0, size, PROT_READ, 0, fd, 0);
    for (i = 0; i < size; i++) {
        char c;

        c = f[i];
        putchar(c);
    }

    return 0;
}

But I always receive a segemation fault when accessing f[i]. What am I doing wrong?

1 Answers
Related