简体   繁体   English

如何在C中使用mmap

[英]How to use mmap in c

I've search and I can't seem to find a way on how to use mmap. 我已经搜索过,但似乎找不到如何使用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? 那么,如何从获取pchFile中读取文件? Is pchFile, the array of bytes mapped from mmap? pchFile是从mmap映射的字节数组吗? How do I read at an offset like for say 400 bytes? 如何读取偏移量,例如400字节? Can I have an offset and read only a certain amount eg only read 100 bytes? 我可以有一个偏移量并且仅读取一定量的内容,例如仅读取100个字节吗?

pchFile is just a plain old char * (with fileSize valid bytes accessible). pchFile只是一个普通的旧char * (可访问fileSize有效字节)。 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. 因此,如果您希望以400字节的偏移量指向数据的指针,则可以仅使用&pchFile[400]pchFile + 400进行隐式或显式指针算术运算。

How you limit it to 100 bytes is based on the API you're using; 如何将其限制为100个字节取决于您使用的API。 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). C本身没有指针“长度”的概念(存在用于NUL终止的字符串的API,但是原始文件数据不太可能在有用的位置包含NUL)。 For memcpy / memcmp and friends, you'd pass &pchFile[400] as the source, and pass the size as 100 . 对于memcpy / memcmp和朋友,您将传递&pchFile[400]作为源,并将大小传递为100 For initializing a C++ vector , you'd pass the start and end pointers to the constructor, eg std::vector<char> myvec(&pchFile[400], &pchFile[500]); 为了初始化C ++ vector ,您需要将起始和结束指针传递给构造函数,例如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. 等等。通常,它要么是开始指针和长度,要么是开始指针和结束指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM