Common Phrases in C

These are some common contructs used in C. These are things that the beginning programmer might not know, but will probably need to write.

Input Checking

Sometimes when you're trying to get input, you have to first check for the correct kind of input. If the input is correct, you want to process it, and if not, you want to ignore it and move on.

...
if ( fscanf(data, "%i %f", &i, &f) == 2 ) {
  /* deal with the input */
  ...
} else {
  /* not correct format, throw away rest of line */
  while ( getc(data) != '\n' ) {}
}
...

Without the while ( getc(data) != '\n' ), this bad line of input will hang around and interfere with input you do later in the program, because the program hasn't dealt with it yet.

In the first line, the 2 should be replaced with the number of variables you are trying to read with the fscanf.

Reading a File

Reading in a file is usually done like this. This tries to open the file and checks to make sure it worked. The while loop will be executed for each line in the program (assuming you input one line each time through the loop.

#include <stdio.h>
#define FILENAME "myfile.dat"

int main () {
  FILE* fp;

  /* ... */
  fp = fopen(FILENAME, "r");
  if ( fp == NULL ) {
    printf("Error opening file " FILENAME "\n");
    return 1;
  }
  while ( !feof(fp) ) {
    /* read and process the next line */
    /* ... */
  }
  /* do any final calculations/output */
  return 0;
}