#include #include #include #include #include // Not an ideal implementation of cat -n by far, but it is a start // // CSE 271 // January 2007 // This file contains two improvements over what we had in class: // - It does not print a line number unless it knows there is content // for the line. // - It uses a 4 character-wide line number (%4d) so that the columns // line up (at least for the first 9999 lines of a file). int main(int argc, char *argv[]) { int filetoread; char c; int done = 0; int result; int line=0; char last; if (argc < 2) { printf("We need an argument.\n"); return -1; } /* open a file */ filetoread = open(argv[1], O_RDONLY); if (filetoread == -1) { printf("File is not found.\n"); return -1; } last = '\n'; // so that we print a line first while (done == 0) { /* read the file */ result = read(filetoread, &c, 1); if (result < 1) done=1; else { if(last == '\n') { line++; printf("%4d ", line); } /* print content to the screen */ result = putchar(c); if (result == EOF) { printf("Output failure.\n"); return -1; } last = c; } } /* close the file */ close(filetoread); return 0; }