Novice Novice - 6 months ago 64
C Question

How to use mmap in c

I've search and I can't seem to find a way on how to use mmap. This is what I have..

char *pchFile;
if ((pchFile = (char *) mmap (NULL, fileSize, PROT_READ, MAP_SHARED, fd, 0)) == (char *) -1){
fprintf(stderr, "Mmap Err: \n");
exit (1);

So, how do I from obtaining pchFile, read from the file? Is pchFile, the array of bytes mapped from mmap? How do I read at an offset like for say 400 bytes? Can I have an offset and read only a certain amount e.g only read 100 bytes?


pchFile is just a plain old char * (with fileSize valid bytes accessible). So if you want a pointer to the data at an offset of 400 bytes, you can just use &pchFile[400] or pchFile + 400 for implicit or explicit pointer arithmetic.

How you limit it to 100 bytes is based on the API you're using; C itself has no concept of the "length" of a pointer (there are APIs for NUL-terminated strings, but raw file data isn't likely to have NULs in useful places). For memcpy/memcmp and friends, you'd pass &pchFile[400] as the source, and pass the size as 100. For initializing a C++ vector, you'd pass the start and end pointers to the constructor, e.g. std::vector<char> myvec(&pchFile[400], &pchFile[500]);, etc. Usually, it'll either be a start pointer and a length, or a start and end pointer.