Search code examples
cmemory-mapped-filesmemory-mapping

Mmap access file content and perform arithmetic operations


In this issue here someone asked how to make a bit-shift with a file and the suggested way was to use a mmap.

Now this is my mmap:

#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>

extern int errno;

int main(int argc, char *argv[]) {
    int fd;
    void *mymap;
    struct stat attr;

    char filePath[] = "test.txt";
    fd = open(filePath, O_RDWR);
    if (fd == -1) {
        perror("Error opening file");
        exit(1);
    }
    if(fstat(fd, &attr) < 0) {
        fprintf(stderr,"Error fstat\n");
        close(fd);
        exit(1);
    }
    mymap = mmap(0, attr.st_size, PROT_READ|PROT_WRITE, MAPFILE|MAP_SHARED, fd, 0);

    if(mymap == MAP_FAILED) {
        fprintf(stderr, "%s: Fehler bei mmap\n",strerror(errno));
        close(fd);
        exit(1);
    }

    if (munmap(0,attr.st_size) == -1) {
        fprintf(stderr, "%s: Error munmap\n",strerror(errno));
        exit(0);
    }
    if (close(fd) == -1) {
        perror("Error while closing file");
    }
    exit(0);
}

how can I access the data inside the mmap? and how could I perform a bit shift or other arithmetic operations like multiplication or addition or substaction, etc?

Thanks!


Solution

  • You could cast mymap to the type you want to work with, and perform operations like if you were working in memory.

    For instance, before if (munmap(0,attr.st_size) == -1) {

    char *str = (char *)mymap;
    int i;
    for(i=0 ; i<attr.st_size ; i++) {
        str[i] += 3; // add 3 to each byte in the file
    }
    

    or

    for(i=0 ; i<attr.st_size - 1 ; i+=2) {
        str[i] *= str[i+1]; // multiply "odd" chars with the next one
        str[i] >>= 2;       // shift 2 (divide by 4)
    }
    

    After closing map & fd, the file has changed according to the operations above.