I've been having trouble with this part of code for a while now. I'm supposed to store the pixel values from the ppm file in an array and then write them to another file upon a keypress. I've been trying this same piece of code for over a week now and it still doesn't seem to work. Any help is very much appreciated (this isn't all my code but only the bits relevant to the question). What seems to happen is that the code seems to stop running after reading in the file for writing so I have no idea if the array is even successfully allocated. Sorry if its a bit of a mess, I was more focused on functionality than neatness.
#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;
}