c - 是否可以使用 mmap 映射文件的一部分?

标签 c memory pointers memory-management memory-mapped-files

我有一个输入文件,其标题如下:

P6\n
width\n
height\n
depth\n

然后将一个结构 pixel* 写入该文件,该文件将被映射。

因此,我想跳过 header 并让我的 mmap 函数返回指向该结构的指针。我怎样才能做到这一点?也许与 lseek ?你能举个例子吗?

我会在这里留下我的部分代码:

printf("Saving header to output file\n");
    if (writeImageHeader(h, fpout) == -1) {
        printf("Could not write to output file\n");
        return -1;
    }

    last_index = (int)ftell(fpout);
    //printf("offset after header= %d\n",last_index);

    //alloc mem space for one row (width * size of one pixel struct)
    row = malloc(h->width * sizeof (pixel));

    /*Create a copy of the original image to the output file, which will be inverted*/
    printf("Starting work\n");
    for (i = 0; i < h->height; i++) {
        printf("Reading row... ");
        if (getImageRow(h->width, row, fpin) == -1) {
            printf("Error while reading row\n");
        }
        printf("Got row %d || ", (i + 1));

        printf("Saving row... ");
        if (writeRow(h->width, row, fpout) == -1) {
            printf("Error while reading row\n");
        }
        printf("Done\n");
    }


    /*Open file descriptor of the ouput file.
     * O_RDWR -  Read and Write operations both permitted
     * O_CREAT - Create file if it doesn't already exist
     * O_TRUNC - Delete existing contents of file*/
    if ((fdout = open(argv[2], O_RDWR, FILE_MODE)) < 0) {
        fprintf(stderr, "Can't create %s for writing\n", argv[2]);
        exit(1);
    }

    /*Get size of the output file*/
    if (fstat(fdout, &sbuf) == -1) {
        perror("Stat error ---------->\n");
        exit(1);
    }
    //printf("Size of output file: %d\n",(int)sbuf.st_size);

    /*Maps output file to memory*/
    if ((data = mmap((caddr_t) 0, sbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fdout, 0)) == (caddr_t) (-1)) {
        perror("Error mmaping");
        exit(EXIT_FAILURE);
    }

如您所见,现在我的 ppm 图像映射到 char* 数据,但我想跳过标题并只映射到 pixel* 部分。

这是我的代码,建议使用 2 个指针,一个来自 mmap 的 char*,另一个等于那个 + 偏移量。

main
c functions
header
makefile

最佳答案

如果您阅读mmap 的手册页,您会发现它的最终参数是off_t offset。说明:

... continuing or at most 'len' bytes to be mapped from the object described by 'fd', starting at byte offset 'offset'.

我怀疑如果您将偏移量作为该参数传递,它会执行您想要的操作。

关于c - 是否可以使用 mmap 映射文件的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4262798/

相关文章:

python - netcdf 文件中数组的压缩

c - 从函数返回字符串(字符数组、字符指针等)

c++ - any_cast std::any 指向特定指针类型的指针

使用 clang 编译带有 readline 支持的 C 程序

c++ - x86 架构中的指令解码

c - 如何有效地合并 Ruby C API 中的两个散列?

类对象数组中的 C++ 内存

c++ - 如何使我的依赖项调用我的全局运算符 new?

C 实现二叉搜索树

c - 在 DirectFBCreate 之后未调用 SIGSEGV 信号处理程序