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][COMMENT_ARRAY_SIZE + 1]; //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);
- 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;
- 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]", 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_WIDTH * MAX_PIXEL_HEIGHT) &&
- fscanf(fd, "%d %d %d", newPPMFile->rgbPixels[counter][0], newPPMFile->rgbPixels[counter][1], newPPMFile->rgbPixels[2]) != EOF) {
- printf("%d %d %d", newPPMFile->rgbPixels[counter][0], newPPMFile->rgbPixels[counter][1], newPPMFile->rgbPixels[2]);
- counter++;
- }
- //close file
- fclose(fd);
- //free unused memory??
- //free(newPPMFile);
- return newPPMFile;
- };
Advertisement
Add Comment
Please, Sign In to add comment