Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define COMMENT_LENGTH 256
- #define COMMENT_ARRAY_SIZE 10
- #define MAX_PIXEL_HEIGHT 480
- #define MAX_PIXEL_WIDTH 640
- struct PPM {
- char format[2 + 1]; //2 letter code for PPM format, +1 for 2 spaces
- char comments[COMMENT_LENGTH + 1][COMMENT_ARRAY_SIZE]; //comment array - n+1 size array to store n values
- int width; //number of columns
- int height; //number of rows
- int max; //maximum colour value (usually 255)
- int rgbPixels[MAX_PIXEL_WIDTH * MAX_PIXEL_HEIGHT][3]; //integers between 0 and max for pixel i's RGB values
- }PPM;
- struct PPM * getPPM(FILE *fd);
- void showPPM(struct PPM *i);
- int main(int argc, char **argv) {
- FILE *file = fopen("ape.ppm", "r");
- if(file == NULL) return 0;
- else {
- struct PPM *newPPM = getPPM(file);
- if(newPPM == NULL) return 1;
- printf("\n");
- showPPM(newPPM);
- return 0;
- }
- }
- struct PPM * getPPM(FILE *fd) {
- if(fd == NULL) {
- return NULL;
- }
- struct PPM *newPPMFile = /*(PPM *)*/ malloc(sizeof(PPM)); //casting result of malloc can potentially mask errors and is unnecessary
- fscanf(fd, "%2s\n", newPPMFile->format);
- //printf("%2s\n", newPPMFile->format);
- //check for comments
- int i = 0;
- while(i < COMMENT_ARRAY_SIZE && fscanf(fd, "# %79[^\n] \n", newPPMFile->comments[i]) == 1) {
- //printf("%s\n", newPPMFile->comments[i]);
- i++;
- }
- //read width and height
- //fscanf(fd, "%d %d", &newPPMFile->width, &newPPMFile->height);
- if (fscanf(fd, "%d %d", &newPPMFile->width, &newPPMFile->height) != 2) {
- //printf("%s\n", "Error reading width & height\n");
- return NULL;
- }
- //printf("%d %d\n", newPPMFile->width, newPPMFile->height);
- //read max
- if(fscanf(fd, "%d", &newPPMFile->max) != 1) {
- //printf("%s\n", "Error reading max\n");
- return NULL;
- }
- //printf("%d\n", newPPMFile->max);
- //read rgb data in rgb array
- int counter = 0;
- while(counter < (MAX_PIXEL_HEIGHT * MAX_PIXEL_WIDTH) &&
- fscanf(fd, "%d\n%d\n%d\n", &newPPMFile->rgbPixels[counter][0], &newPPMFile->rgbPixels[counter][1], &newPPMFile->rgbPixels[counter][2]) != EOF) {
- //printf("%d %d %d\n", newPPMFile->rgbPixels[counter][0], newPPMFile->rgbPixels[counter][1], newPPMFile->rgbPixels[counter][2]);
- counter++;
- }
- //close file
- fclose(fd);
- //free unused memory??
- //free(newPPMFile);
- return newPPMFile;
- }
- void showPPM(struct PPM *i) {
- printf("%s\n", i->format);
- //print comments array
- int x;
- for(x = 0; x < sizeof(i->comments) / sizeof(i->comments[0]); x++) {
- printf("# %s\n", i->comments[x]);
- }
- printf("%d %d\n", i->width, i->height);
- printf("%d\n", i->max);
- //print rgb values
- for(x = 0; x < 500; x++) {
- printf("%d %d %d\n", i->rgbPixels[x][0], i->rgbPixels[x][1], i->rgbPixels[x][2]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment