the published program is much more complicated and contains several problems associated with indexing into arrays and how data is written to the output file.
The following code contains comments, performs appropriate error checking, and creates the desired image file.
#include <stdio.h> // fopen(), fclose(), fprintf(), FILE
#include <stdlib.h>
#include <errno.h> // errno
#include <string.h> // strerror()
#define MAX_ROWS (800)
#define MAX_COLS (800)
#define BOARD_SIZE (800)
#define SQUARE_SIZE (100)
int main (int argc, char* argv[])
{
int row;
int col;
if( 2 != argc )
{
fprintf( stderr, "USAGE: %s <PGM_filename>\n", argv[0]);
exit( EXIT_FAILURE );
}
FILE* image = fopen(argv[1], "wb");
if (!image)
{
fprintf(stderr, "Can't open output file %s for write, due to: %s\n", argv[1], strerror( errno ) );
exit( EXIT_FAILURE);
}
fprintf(image, "P5\n%d %d\n255\n", BOARD_SIZE, BOARD_SIZE);
for (row = 0;row < BOARD_SIZE; row++)
{
for (col = 0;col < BOARD_SIZE; col++)
{
if( (row/SQUARE_SIZE)%2 == 0 )
{
if( (col/SQUARE_SIZE)%2 == 0 )
{
fprintf( image, "%c", 255 );
}
else
{
fprintf( image, "%c", 0 );
}
}
else
{
if( (col/SQUARE_SIZE)%2 == 0 )
{
fprintf( image, "%c", 0 );
}
else
{
fprintf( image, "%c", 255 );
}
}
}
}
fclose(image);
return 0;
}
source
share