/* Program to list a text file to the screen, with line numbers. */ #include #include main () { FILE * fin; char fname[81]; int ch, previous_ch, line_num = 1; printf("Enter name of file to read: "); scanf("%80s", fname); fin = fopen(fname, "r"); if (fin == NULL) { fprintf(stderr, "File cannot be opened.\n"); exit(1); } /* Method: generate a line number when the previous character is '\n' */ previous_ch = '\n'; while ((ch = getc(fin)) >= 0) { /* while not eof */ if (previous_ch == '\n') { /* Start of a line? */ fprintf(stderr, "%4d ", line_num); line_num++; } putc(ch, stderr); previous_ch = ch; } fclose(fin); }