I01 Answer


#include <stdio.h>
#include <stdlib.h>

/* Puzzle I01 -- create an image file with all pixels the same level
|
|  The name of the file, the number of rows and number of columns,
|  and the gray level are specified on the command line.
|
*/
int main(int argc, char *argv[])
{
  int r, nrows, c, ncols, grayLevel;
  FILE *image;

  /* check the command line parameters */
  if ( argc != 5 )
  {
    printf("makeGray fileName.pgm nrows ncols grayLevel\n");
    return 0;
  }

  nrows = atoi( argv[2] );
  if ( nrows < 1 )
  {
    printf("number of rows must be positive\n");
    return 0;
  }

  ncols = atoi( argv[3] );
  if ( nrows < 1 )
  {
    printf("number of columns must be positive\n");
    return 0;
  }

  grayLevel = atoi( argv[4] );
  if ( !(grayLevel >= 0 && grayLevel <=255) )
  {
    printf("grayLevel must be between 0 and 255\n");
    return 0;
  }

  /* open the image file for writing */
  if ( (image = fopen( argv[1], "wb") ) == NULL )
  {
    printf("file %s could not be created\n", argv[1]);
    return 0;
  }

  /* write out the PGM Header information */
  fprintf( image, "P5 ");
  fprintf( image, "# Created by makeGray\n");

  /* width, height, number of gray levels */
  fprintf( image, "%d %d %d ", ncols, nrows, 255 );

  /* write out the pixel data */
  for ( r=0; r<nrows; r++ )
    for ( c=0; c<ncols; c++ )
      fputc( grayLevel, image );

  /* close the file */
  fclose ( image );

  return 1;
}

Comments:

(1) This program uses functions from the standard I/O library to create the disk file. Check a book on C if you are not familiar with them.

(2) The statement

nrows = atoi( argv[2] )

converts the string of characters pointed to by argv[2]into an int.

(3) The statement

if ( (image = fopen( argv[1], "wb") ) == NULL )

creates a disk file with a name given by argv[1], which is the parameter on the command line immediately after the program name. The string "wb" stands for "write binary" which means the file is opened for writing and is expected to contain at least some bytes that are not ASCII-encoded characters. If the system fails to create the image (perhaps it already exists and is "read only"), fopen() returns NULL.

(4) It is easy to write out the header information incorrectly. This is because the header lists width then height, not number of rows then number of columns.


back