用于数据数组的mmap函数

问题描述 投票:0回答:1

假设您有一个二进制文件。它由双人组成。它的大小足够小,可放入内存中。如何使用mmap函数读取所有这些数字?我试图取消引用输出指针。但它只是数据的第一要素。要使用循环,如何控制数组元素的数量是非常重要的。

int main(int argc, char* argv[]) { // we get filename as an argument from the command line
    if (argc != 2)
        return 1;
    int fd = open(argv[1], O_RDWR, 0777);
    size_t size = lseek(fd, 0, SEEK_END);
    double m = 0;
    int cnt = 0; // counter of doubles
    void* mp = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
    if (mp == MAP_FAILED)
        return 1;
    double* data = mp;
    m += *data; // we want to count the sum of these doubles
    ++cnt;
    int ump_res = munmap(mp, sizeof(double));
    if (ump_res < sizeof(double))
        return 1;
    printf("%a\n", (m / (double)cnt)); // we output the average number of these doubles
    close(fd);
    return 0;
}

我希望在stdout中我们将得到文件中所有双打的平均值,这个名字在argv[1]中给出。

c unix double mmap
1个回答
1
投票

有可能将void*转换为double*。然后你可以迭代并处理元素:

void* mp = mmap(0, length, PROT_READ, MAP_PRIVATE, fd, 0);
    if (mp == MAP_FAILED) {
        close(fd);
        return 1;
    }
    double* data = (double*)mp;
    size_t cnt = length / sizeof(double);
    for (size_t i = 0; i < cnt; ++i) {
        m += data[i];
    }

希望你会发现它有用。

© www.soinside.com 2019 - 2024. All rights reserved.