【发布时间】:2022-01-26 14:52:37
【问题描述】:
这部分代码我已经有一段时间了。我应该将 ppm 文件中的像素值存储在一个数组中,然后在按键时将它们写入另一个文件。一个多星期以来,我一直在尝试同一段代码,但它似乎仍然不起作用。非常感谢任何帮助(这不是我的全部代码,而只是与问题相关的部分)。似乎发生的情况是,在读取文件进行写入后,代码似乎停止运行,所以我不知道数组是否已成功分配。对不起,如果它有点乱,我更注重功能而不是整洁。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RGB_COMPONENT_COLOUR 255
#define height 1080
#define width 1920
typedef struct
{
unsigned char red, green, blue;
} PPMPixel;
typedef struct
{
int x, y;
PPMPixel *data;
} PPMImage;
int main(PPMImage *readPPM())
{
char key = 0;
do
{
printf("\tPress r to read in an image in ppm format\n");
printf("\tPress s to save image in ppm format\n");
printf("\tPress q to quit\n");
{
scanf("\t %c", &key);
fseek(stdin, 0, SEEK_END);
switch(key)
{
FILE *fp, *pf;
PPMImage *img;
int i, j;
int **array = malloc(height * sizeof(int*));
array[i] = malloc(width * sizeof(int));
case 'r' :
{
char buff[16];
int c, rgb_comp_colour;
int e;
char fname[100];
printf("Enter file name: ");
scanf("%s", fname);
fseek(stdin,0,SEEK_END);
fp = fopen(fname, "r");
if (fp == NULL)
{
printf("\tError while opening the file\n");
}
else
{
printf("\tReading in %s\n", fname);
}
if (fp)
{
while ((e = getc(fp))!=EOF)
putchar(e);
if (!array)
{
perror("\tError occured allocating memory to the array\n");
exit(1);
}
else
{
printf("\tMemory allocated to the array successfully\n");
}
for(i=0;i<width;i++)
{
for(j=0;j<height;j++)
{
fseek(fp, 0, SEEK_SET);
fscanf(fp, "%d", &array[i][j]);
}
}
else
{
printf("\tCould not successfully allocate array\n");
}
}
break;
case 's' :
{
char fname2[100];
printf("Enter file name: ");
scanf("%s", fname2);
fseek(stdin,0,SEEK_END);
pf = fopen(fname2, "w");
if (pf == NULL)
{
printf("\tError while opening the file\n");
}
else
{
printf("\tWriting in %s\n", fname2);
}
for(i=0;i<width;i++)
{
for(j=0;j<height;j++)
{
fseek(pf, 0, SEEK_SET);
fprintf(pf, "%d ", array[i][j]);
}
}
if (!array[i][j])
{
printf("File write error");
}
else
{
printf("File written successfully");
}
}
break;
case 'q' : //If q is pressed the code ends and a message is printed so the user knows the program has been terminated.
{
printf("\tTerminating program...\n");
}
break;
default: //If anything other than the specified case statement key presses is entered, the code is looped again and an error message is printed.
{
printf("\tInvalid Input\n");
}
fclose(fp);
fclose(pf);
free(array);
free(array[i]);
free(img);
}
}
}
while(key != 'q');
return 0;
}
【问题讨论】:
-
旁白:为什么scanf格式字符串开头有
\t? -
array[i] = malloc(width * sizeof(int));你还没有分配i。 -
该行应该在
for(i...)循环内。 -
fscanf(fp, "%d", &array[i][j]);将尝试读取文本整数。您只想为 rgb 读取 3 个字节的二进制文件。为什么你还有array?您不应该直接读取PPMImage.data数组吗?
标签: arrays c image-processing file-io switch-statement