The first step is to learn how to
indent code consistently.
Code:
struct PGMstructure {
int maxVal;
int width;
int height;
unsigned char data[800][800];
};
int main()
{
FILE *imagein, *imageout;
char ch;
int row, col, type;
int num_elements;
int i, j;
int ch_int;
struct PGMstructure *imginfo;
char fpath[1000], tpath[1000];
printf("Enter PGM file path:");
scanf("%s", fpath);
imagein = fopen(fpath, "r+");
if (imagein == NULL) {
printf("Error opening first file");
exit(8);
}
while (getc(imagein) != '\n');
while (getc(imagein) == '#') {
while (getc(imagein) != '\n');
}
fseek(imagein, -1, SEEK_CUR);
fscanf(imagein, "%d", &imginfo->width);
fscanf(imagein, "%d", &imginfo->height);
fscanf(imagein, "%d", &imginfo->maxVal);
printf("\n width = %d\n", imginfo->width);
printf("\n height = %d\n", imginfo->height);
printf("\n maxVal = %d\n", imginfo->maxVal);
for (row = imginfo->height - 1; row >= 0; row--) {
for (col = 0; col < imginfo->data; col++) {
fscanf(imagein, "%d", &ch_int);
imginfo->data[row][col] = ch_int;
}
}
printf("Enter path of output file:");
scanf("%s", tpath);
imageout = fopen(tpath, "w+");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
fprintf(imageout, "%d", imginfo->data[row][col]);
}
printf("\n");
}
return 0;
}
> However I am getting some problems, the program stops running suddenly. I am not sure where the problem is :
How do you know it's stopped?
- do you get a command prompt back?
- does it pop up some error message like "this program has stopped working" ?
Is the behaviour consistent?
Say for example one .pgm file always works, and another always fails. If so, study the apparent differences and consider how that affects your code.
Are all your input files less than 800x800 in size? If either is exceeded, your code will blow up.
For example, your code to deal with comment lines (beginning with #) is extremely fragile. The spec says comments can appear anywhere, but you assume a specific place.
> struct PGMstructure *imginfo;
Probably the biggest mistake of all, where is the memory for this pointer allocated?
You can't just declare a pointer, then go do things like imginfo->member without considering how imginfo has been initialised to point to some usable memory.
Have you tried to use a debugger?
What is the purpose of the final printf("\n") in the last loop? Did you mean to write this to the file?
> scanf("%s", fpath);
I hope you don't have filenames with spaces in, otherwise it just won't work.
> imagein = fopen(fpath, "r+");
Why the + in all the modes? You're not updating any files, it's straight forward read from one, write to another.
> fprintf(imageout, "%d", imginfo->data[row][col]);
If you're trying to create another .pgm file, then you need to space separate the pixel values.