Tag Archives: file-io

Some arg checking and file IO in C

This small program reads a filename from the command line, and reads the file, while printing the line number in front of it.

// Line Number.
#include <stdio .h>
 
void printnumber(int number);
 
int main(int argc, char *argv[]) {
  int c;
  int lines = 1;
  FILE *fh;
 
  if (argc < 2) {
    printf("ERROR: Need a filename as argument.\n");
    return 1;
  }
 
  fh = fopen(argv[1], "r");
 
  printnumber(lines);
  while ((c = getc(fh)) != EOF) {
    if (c == '\n') {
      lines++;
      printnumber(lines);
    }
    else {
      printf("%c", c);
    }
  }
  return 0;
}
 
void printnumber(int number) {
  printf("\n%3d|", number);
}