c - mmap访问文件内容并执行算术运算

标签 c memory-mapped-files memory-mapping

本期here有人问如何对文件进行位移位,建议的方法是使用 mmap。

现在这是我的 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);
}

如何访问 mmap 内的数据?我如何执行位移或其他算术运算,如乘法、加法或减法等?

谢谢!

最佳答案

您可以将 mymap 转换为您想要使用的类型,并执行操作,就像在内存中工作一样。

例如,在 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
}

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)
}

关闭map&fd后,文件按照上面的操作发生了变化。

关于c - mmap访问文件内容并执行算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47436137/

相关文章:

c - GSM PDU 解码算法行为异常

c - 中点规则 - C 中的数值方法

c - 图标显示在窗口上但不显示在 .exe 文件上 (gtk3 windows7)

c# - 将流上的编码更改为 UTF-8 (MemoryMappedViewStream)

java - C++中的内存映射文件用Java读取

java - Java 中的内存映射集合

对检查和比较句子中最后三个单词的任务感到困惑

c++ - 内存映射文件的奇怪行为,一些观察和一些问题

c - 如何从C中的内存映射文件读取bin文件(FAT16分区)?

c++ - 模拟游戏机的内存映射,根据提供的地址访问不同的位置