title: Error handling while reading file in C
body: <p>I'm finishing my C implementation of Conway's Game of Life, and I have a problem with error handling when parsing incorrect netting file.</p>
  
  <p>File format is:</p>
  
  <pre><code>rows cols
  x1   y1
  x2   y2
  </code></pre>
  
  <p>Reading function:</p>
  
  <pre><code>net_t *file_to_net( net_t *n, char *filename )
  {
  assert( n != NULL );
  
  FILE *f = fopen( filename, "r" );
  if( f == NULL )
      print_error_file( filename );
  
  if( fscanf( f, "%d %d", &amp;(n-&gt;rows), &amp;(n-&gt;cols) ) != 2 )
      print_error("net");
  
  n-&gt;vec = calloc( n-&gt;rows * n-&gt;cols, sizeof(unsigned char) );
  if( n-&gt;vec == NULL )
      print_error("alloc");
  
  int i, x, y;
  while( fscanf( f, "%d %d", &amp;x, &amp;y ) == 2 )
  {
      if( x &gt; n-&gt;rows || y &gt; n-&gt;cols )
      {
          fprintf( stderr, "%sERROR:%s Coordinates of living cell in net file is bigger then net dimensions.\n", COLOR_RED, COLOR_RESET );
          exit(EXIT_FAILURE);
      }
  
      i = ( n-&gt;cols * (x - 1) ) + (y - 1);
      n-&gt;vec[i] = 1;
  }
  if( !feof(f) )
      print_error("net");
  
  fclose(f);
  
  return n;
  }
  </code></pre>
  
  <p>Error handling works when there are letters instead of digits (while loop ends, but not EOF), but it doesn't work when I don't have one of the coordinates (there is an odd number of numbers), for example:</p>
  
  <pre><code>50 50
  2 3
  3 4
  4
  4 3
  4 4
  </code></pre>
  
  <p>does not end with error.
  I've been trying to implement it, but I can't make it work in all 3 cases (good file, non-digits inside and odd number of numbers).</p>
  
  <hr>
  
  <p>EDIT</p>
  
  <p>OK, thanks very much for the help. Ended with this code of the loop, which covers all three cases:</p>
  
  <pre><code>int i, x, y;
  int pos;
  while( fgets( line, MAXL, f ) != NULL )
  {
      if( sscanf( line, "%d %d %n", &amp;x, &amp;y, &amp;pos ) != 2 )
      {
          print_error("net");
      }
      else if( line[pos] != '\0' )
      {
          print_error("net");
      }
  
  
      if( x &gt; n-&gt;rows || y &gt; n-&gt;cols )
      {
          fprintf( stderr, "%sERROR:%s Coordinates of living cell in net file is bigger then net dimensions.\n", COLOR_RED, COLOR_RESET );
          exit(EXIT_FAILURE);
      }
  
      i = ( n-&gt;cols * (x - 1) ) + (y - 1);
      n-&gt;vec[i] = 1;
  }
  </code></pre>