In: Computer Science
Using C, use mmap() to map a file to memory, and then search through it.
For example, get and print out the first character of each line in the file:
abc
def
ghi
Hi,
mmap as a way of mapping physical memory to address space. But mmap is known for its ability to map files to the address space also.
Here is the code for above-mentioned question. I commented in between for better understanding.
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(void) {
int fd = open("words", O_RDONLY);
size_t pagesize = getpagesize();
//mapping the file named words to the memory using mmap
char * region = mmap(
(void * )(pagesize * (1 << 20)),
pagesize,
PROT_READ, MAP_FILE | MAP_PRIVATE,
fd, 0
);
//printing first charecter
if ( * region != '\0') {
printf("%c", * region++);
}
//loop to print first charecter of every line
while ( * region != '\0') {
if ( * region == '\n') {
printf("\n%c", *++region);
}
* region++;
}
//fwrite(region, 1, pagesize, stdout);
int unmap_result = munmap(region, pagesize);
close(fd);
return 0;
}