【发布时间】:2011-05-14 20:24:38
【问题描述】:
我有一个输入文件,其标题如下:
P6\n
width\n
height\n
depth\n
然后在这个文件中写入一个结构,pixel*,该文件将被映射。
所以,我想跳过标题并让我的 mmap 函数将 ptr 返回到该结构。我怎样才能做到这一点? 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*,另一个等于 + offset。
【问题讨论】:
-
为什么不只使用一点指针算法和一个指针变量?
-
请注意,
caddr_t是 ANSI C 之前的旧式废话。mmap使用的类型是void *。 -
@R..:那么我怎样才能以正确的方式调用 mmap?这是来自一个老师的例子,lol
-
你可以在这里找到
mmap的正确原型和用法:opengroup.org/onlinepubs/9699919799/functions/mmap.html 如果你的老师试图“纠正”你并坚持写caddr_t废话,这可能会很有用。
标签: c memory pointers memory-management memory-mapped-files