Reputation: 21
I'm having trouble figuring out how to read in a ppm file into the standard input, storing the pixels in a 2- dimensional array of new_pix in C. I don't really know How to get it started. Thanks in advance!
Upvotes: 0
Views: 568
Reputation: 588
I assume you can get the dimensions of the image from the file (call them W
and H
). If not, read about the format from wikipedia
Now, you need to allocate memory for the 2d-array you want to make. You will need a char **buf
(assuming 8-bit grayscale. You can use long
or long long
for 32/64 bit images.
Next allocate the space for pointers where you will store the rows of the image.
buf=(char**)malloc(sizeof(char*)*H);
Next, you need to allocate space for each row and read it from stdin (you can use scanf
in a loop).
for(int y=0;y<H;y++){
buf[y]=(char*)malloc(sizeof(char)*W);
for(int x=0;x<W;x++)
scanf("%d",&buff[y][x]);
}
And you are done! Note that you will have to do checks on malloc return value and limit W and H to sane values if you plan to distribute the code.
Upvotes: 1