Search code examples
carraysprintingpixel

Are my solutions to printing an error due to file size and storing values right?


PART 1: What I need to do is print out an error if the file size exceeds the 500 by 500 measurements (defined at the top as max_width and height). I

PART 2: The other part is that I have to read the pixel information from the input file and store it into a 2d array. Each pixel has 3 values for red, green, and blue, but I'm not sure if this matters.

My attempt at the solution:

PART 1:

void check_file_size //I'm not sure what to put as arguments since width/height are global
{
   if (width > 500 && height > 500)
   {
      perror("Error: File size too big.\n");
   }
}

PART 2:

#define max_width 500
#define max_height 500
int width, height

void read_header(FILE *new)
{
   int max_color;
   char P[10];

   fgets(P, 10, new);
   fscanf(new, "%d %d", &width, &height);
   fscanf(new, "%d", &max_color);
}

void store_into_array(FILE *input)
{
   int array[max_width][max_height];

   for (x = 0; x < width; x++)
   {
      for (y = height; y >=0; y--)
      {
         fscanf(input, "%d", &array[x][y]);
      }
   }
}

Solution

  • Part 1

    1. Function should take void arguments - this means none.
    2. You want an or. Error if width OR height are too big.
    3. Minor style note, you should be using the #defines here and they should be all uppercase.

    void check_file_size(void) {
        if (width > MAX_WIDTH || height > MAX_HEIGHT) {
            perror("Error: File size too big.\n");
        }
    }
    

    Part 2

    You can loop through an array here like you are, but it's actually much nicer to cheat. A C array of arrays or a straight array is the same thing with slightly different syntactic sugar.

    1. Read the whole file into an array, see Reading the whole text file into a char array in C for implementation hints.
    2. Cast the buffer into the final structure that you want.

    // Make struct rgb match your data, details not supplied in the question
    struct rgb {
        uint8_t red;
        uint8_t green;
        uint8_t blue;
    }
    
    // Get width & height info as before
    
    uint32_t buffer_size;
    void* buffer;
    load_file('filename', buffer, &buffer_size);
    
    // Should verify that buffer_size == width * height * 3
    
    struct rgb (*image_data)[width] = (struct rgb(*)[width])buffer;
    // Note the above variable length array is a C99 feature
    // Pre-C99 the same trick is a touch more ick
    
    // Data can now be accessed as image_data[x][y].red; etc.
    

    Sorry about the stdint.h variables, a habit I can't (and don't want to) break.