/* This program reads a file line by line and prints those lines to the screen. It behaves just as the Unix program 'cat' does. */ #include <stdio.h> main() { char fname[200]; // Here we hold the file name char line[1000]; // Here we hold the contents of each line char *ret; // This is the return value from fgets FILE *fp; // This is the file pointer to the file we read printf("Give file name: "); gets(fname); printf("I will now type file \"%s\"\n", fname); fp = fopen(fname, "r"); // This opens the file for reading only // and creates the file pointer 'fp' read_line: ret = fgets(line, 998, fp); // This reads one line from fp, into variable // line, up to 998 chars if( ret != NULL ) { // if fgets returns non-NULL then a line was indeed read printf("%s", line); // we print this line to the screen goto read_line; // back to read another line } fclose(fp); // a NULL value was returned from fgets indicating that // the file has been exhausted, so we close it and finish }