【发布时间】:2016-02-09 11:05:06
【问题描述】:
所以我已经阅读了一些与此相关的问题,但没有一个能解决我的问题。我目前正在尝试读取 P6 ppm 文件(它是一个二进制文件)。我当前的代码是
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct pixel {
char red;
char green;
char blue;
};
int main(int argc, char **argv)
{
char type[3];
int numRow, numCol, maxNum;
FILE *oldFile, *newFile;
struct pixel currentPixel;
char buffer[5];
oldFile = fopen(argv[1], "rb");
if(oldFile == NULL) {
fprintf(stderr, "Could not open file %s for reading in binary", argv[1]);
return 0;
}
fscanf(oldFile, "%2s", type);
type[2] = '\0';
if(strcmp(type, "P6") != 0) { //Make sure we have a P6 file
printf("This file is not of type P6");
return 0;
}
newFile = fopen(argv[2], "wb");
fprintf(newFile, "%s\n", type);
/*Read number of columns
rows and
The max number that can represent a colour*/
fscanf(oldFile, "%d", &numCol);
fscanf(oldFile, "%d", &numRow);
fscanf(oldFile, "%d", &maxNum);
/*Print the information to newFile*/
fprintf(newFile, "%d %d\n", numCol, numRow);
fprintf(newFile, "%d\n", maxNum);
fseek(oldFile, 1, SEEK_CUR);
fread(¤tPixel, sizeof(struct pixel), 1, oldFile);
printf("%c %c %c", currentPixel.red, currentPixel.green, currentPixel.blue);
fclose(newFile);
fclose(oldFile);
return 0;
}
所以开头有效,我的 newFile 包含 P6、3、3 和 255 行。然后我尝试使用 fread 行读取实际像素。这是它失败的地方,我不知道为什么。它目前在钻石内部打印出两个问号。我目前只尝试读取构成一个像素的前三个数字(一个红色分量,一个绿色和一个蓝色)。
我也有同一张图片的P3文件,P3文件长这样:
P3
3 3
255
0 255 255 0 0 0 0 0 255
255 0 255 100 100 100 255 0 0
255 255 0 255 255 255 0 255 0
所以二进制文件应该像这样设置,但只是二进制格式。当我输入
od -c binaryImage.ppm
我明白了
0000000 P 6 \n 3 3 \n 2 5 5 \n \0 377 377 \0 \0
0000020 \0 \0 \0 377 377 \0 377 X X X 377 \0 \0 377 377 \0
0000040 377 377 377 \0 377 \0
0000046
我不确定为什么我的 fread 函数不起作用。不确定是否相关,但我正在 Linux Ubuntu 上编译
gcc -Wall rotate.c -o 旋转
【问题讨论】:
-
@WeatherVane 前三行是常规文本。使用
fscanf读取那些可以正常工作,但之后我们需要使用fread读取,因为文件的其余部分是用二进制编写的 -
为什么将 RGB 值打印为字符 (%c) 而不是数字 (%d)?这就是你在输出中得到奇怪符号的原因。
-
@BrunoBellucci 这是个好问题。我改变了我的代码,所以我把它们变成了整数,而不是红色、绿色和蓝色。它现在打印出
16776960 0 -16711681 -
没有。您的像素值应该是 char,但您需要将它们打印为整数。
-
@BrunoBellucci 打印出
0 -1 -1
标签: c struct binaryfiles ppm