Reputation: 121
int i, j;
for (i = (*pgm).height - 1; i >= 0; i--)
for (j = 0; j < (*pgm).width; j++)
{
fscanf(file, "%c", &(*pgm).data[i][j]);
}
}
This is a part of my function for reading a PGM file byte by byte. In this for, after something like 2000 bytes, every byte that it reads is 0.
Instead of reading the image like this
I get it like this
How can i solve this?
Edit: this is the definition of the pgm:
typedef struct PGM
{
int width;
int height;
int maxValue;
unsigned char data[500][500];
} PGM;
Upvotes: 1
Views: 516
Reputation: 241671
If you are using Windows, you need to make sure that you open the file in binary mode. Otherwise, a byte which happens to have the value 26 (0x1A) will be interpreted as an end of file, after which no further bytes will be read. (Other modifications will also be made, which will produce other problems.)
On any OS, it is best to open binary files in binary mode, but on Windows it is hugely important.
It is also important to check the return value of fscanf.
Fscanf is an awful way of reading a binary file, for what its worth. If your teacher told you to do that, you might want to have a discussion with him about good programming practice.
Upvotes: 1