cat.c (2680B)
1 /* 2 * PROG: -b: Number the non-blank output lines, starting at 1 3 * TODO: -e: Display non-printing characters (see the -v option), and display a dollar sign ('$') at the end of each line 4 * TODO: -l: Set an exclusive advisory lock on the standard output file descriptor. 5 * DONE: -n: Number the output lines, starting at 1 6 * TODO: -s: Squeeze multiple adjacent empty lines, causing the output to be single spaced 7 * TODO: -t: Display non-printing characters (see the -v option), and display tab characters as '^I' 8 * TODO: -u: Disable output buffering 9 * TODO: -v: Display non-printing characters so they are visible. Control characters print as '^X' for control-X; the delete character (octal 0177) prints as '^?'. Non-ASCII characters (with the high bit set) are printed as 'M-' (for meta) followed by the character for the low 7 bits. 10 */ 11 #include<stdio.h> 12 #include<stdlib.h> 13 #include<string.h> 14 15 int main(int argc, char *argv[]) { 16 17 int nFiles = argc - 1; 18 int i; 19 char ch; 20 FILE *fp; 21 22 /* Implements the '-b' flag */ 23 /* This flag should be re-done to recycle */ 24 /* code rather than re-doing it */ 25 int bNums = strcmp(argv[1], "-b"); 26 if (bNums == 0) { 27 int line = 1; 28 for (i = 2; i <= nFiles; i++) { 29 fp = fopen(argv[i], "r"); 30 if (fp == NULL) 31 { 32 perror("error while opening file\n"); 33 exit(EXIT_FAILURE); 34 } 35 printf("\t%d ", line); 36 while((ch = fgetc(fp)) != EOF) { 37 if (ch == '\n') { 38 line++; 39 printf("\n\t%d ", line); 40 //printf("\n"); 41 ch = fgetc(fp); 42 if (ch == '\n') { 43 printf("\n"); 44 } else { 45 ungetc(ch, fp); 46 } 47 } else { 48 printf("%c", ch); 49 } 50 } 51 fclose(fp); 52 } 53 return 0; 54 } 55 56 /* Implements the '-n' flag */ 57 int lNums = strcmp(argv[1], "-n"); 58 if (lNums == 0) { 59 int line = 1; 60 for (i = 2; i <= nFiles; i++) { 61 fp = fopen(argv[i], "r"); 62 if (fp == NULL) 63 { 64 perror("error while opening file\n"); 65 exit(EXIT_FAILURE); 66 } 67 printf("\t%d ", line); 68 while((ch = fgetc(fp)) != EOF) { 69 if (ch == '\n') { 70 line++; 71 printf("\n\t%d ", line); 72 } else { 73 printf("%c", ch); 74 } 75 } 76 77 fclose(fp); 78 } 79 return 0; 80 } 81 82 /* The following code creates the basic functionality of cat */ 83 for (i = 1; i <= nFiles; i++) { 84 fp = fopen(argv[i], "r"); 85 if (fp == NULL) 86 { 87 perror("error while opening file\n"); 88 exit(EXIT_FAILURE); 89 } 90 while((ch = fgetc(fp)) != EOF) { 91 printf("%c", ch); 92 } 93 94 fclose(fp); 95 } 96 return 0; 97 }