Guest User

Untitled

a guest
Jan 20th, 2016
13
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define COMMENT_LENGTH 256
  6. #define COMMENT_ARRAY_SIZE 10
  7. #define MAX_PIXEL_HEIGHT 480
  8. #define MAX_PIXEL_WIDTH 640
  9.  
  10. struct PPM {
  11. char format[2 + 1]; //2 letter code for PPM format, +1 for 2 spaces
  12. char comments[COMMENT_LENGTH][COMMENT_ARRAY_SIZE + 1]; //comment array - n+1 size array to store n values
  13. int width; //number of columns
  14. int height; //number of rows
  15. int max; //maximum colour value (usually 255)
  16. int rgbPixels[MAX_PIXEL_WIDTH * MAX_PIXEL_HEIGHT][3]; //integers between 0 and max for pixel i's RGB values
  17. }PPM;
  18.  
  19. struct PPM * getPPM(FILE *fd);
  20.  
  21. int main(int argc, char **argv) {
  22. FILE *file = fopen("ape.ppm", "r");
  23. if(file == NULL) return 0;
  24. else {
  25. struct PPM *newPPM = getPPM(file);
  26.  
  27. if(newPPM == NULL) return 1;
  28.  
  29. return 0;
  30. }
  31. }
  32.  
  33. struct PPM * getPPM(FILE *fd) {
  34. if(fd == NULL) {
  35. return NULL;
  36. }
  37.  
  38. struct PPM *newPPMFile = /*(PPM *)*/ malloc(sizeof(PPM)); //casting result of malloc can potentially mask errors and is unnecessary
  39.  
  40. fscanf(fd, "%2s\n", newPPMFile->format);
  41. printf("%2s\n", newPPMFile->format);
  42.  
  43. //check for comments
  44. int i = 0;
  45. while(i < COMMENT_ARRAY_SIZE && fscanf(fd, "%79[^\n]", newPPMFile->comments[i]) == 1) {
  46. printf("%s\n", newPPMFile->comments[i]);
  47. i++;
  48. }
  49.  
  50. //read width and height
  51. //fscanf(fd, "%d %d", &newPPMFile->width, &newPPMFile->height);
  52. if (fscanf(fd, "%d %d", &newPPMFile->width, &newPPMFile->height) != 2) {
  53. printf("%s\n", "Error reading width & height\n");
  54. return NULL;
  55. }
  56. printf("%d %d\n", newPPMFile->width, newPPMFile->height);
  57.  
  58. //read max
  59. if(fscanf(fd, "%d", &newPPMFile->max) != 1) {
  60. printf("%s\n", "Error reading max\n");
  61. return NULL;
  62. }
  63. printf("%d\n", newPPMFile->max);
  64.  
  65. //read rgb data in rgb array
  66. int counter = 0;
  67. while(counter < (MAX_PIXEL_WIDTH * MAX_PIXEL_HEIGHT) &&
  68. fscanf(fd, "%d %d %d", newPPMFile->rgbPixels[counter][0], newPPMFile->rgbPixels[counter][1], newPPMFile->rgbPixels[2]) != EOF) {
  69. printf("%d %d %d", newPPMFile->rgbPixels[counter][0], newPPMFile->rgbPixels[counter][1], newPPMFile->rgbPixels[2]);
  70. counter++;
  71. }
  72.  
  73. //close file
  74. fclose(fd);
  75.  
  76. //free unused memory??
  77. //free(newPPMFile);
  78.  
  79. return newPPMFile;
  80. };
Advertisement
Add Comment
Please, Sign In to add comment