head.c (1889B)
1 /* Terrible implementation of the head core util */ 2 /* For license infomration see the LICENSE file included in this repo */ 3 #include<stdio.h> 4 #include<stdlib.h> 5 #include<string.h> 6 7 int main(int argc, char *argv[]) { 8 FILE *fp; 9 char ch; 10 int lines = 10; // Default number of lines, can be chaged at runtime with -n arg 11 int i = 0; 12 int files = 1; 13 int delimeter = 0; 14 15 int argByte = strcmp(argv[1], "-c"); 16 if (argByte == 0) { 17 int bytes = strtol(argv[2], NULL, 10); 18 files = 3; 19 if (files == (argc - 1)) { 20 fp = fopen(argv[files], "r"); 21 i = 0; 22 while(((ch = fgetc(fp)) != EOF) && (i < bytes)) { 23 printf("%c", ch); 24 i++; 25 } 26 return 0; 27 } else { 28 for (files = files; files < argc; files++) { 29 fp = fopen(argv[files], "r"); 30 i = 0; 31 printf("==> %s <==\n", argv[files]); 32 while(((ch = fgetc(fp)) != EOF) && (i < bytes)) { 33 printf("%c", ch); 34 i++; 35 } 36 fclose(fp); 37 } 38 return 0; 39 } 40 } 41 42 int argLine = strcmp(argv[1], "-n"); 43 if (argLine == 0) { 44 lines = strtol(argv[2], NULL, 10); 45 files = 3; 46 } 47 48 if (files == (argc - 1)) { 49 fp = fopen(argv[files], "r"); 50 while((ch = fgetc(fp)) != EOF) { 51 if (i >= lines) { 52 fclose(fp); 53 i = 0; 54 break; 55 } else if (ch == '\n') { 56 printf("%c", ch); 57 i++; 58 } else { 59 printf("%c", ch); 60 } 61 } 62 return 0; 63 } 64 for (files = files; files < argc; files++) { 65 fp = fopen(argv[files], "r"); 66 printf("==> %s <==\n", argv[files]); 67 while((ch = fgetc(fp)) != EOF) { 68 if (i >= lines) { 69 fclose(fp); 70 i = 0; 71 break; 72 } else if (ch == '\n') { 73 printf("%c", ch); 74 i++; 75 } else { 76 printf("%c", ch); 77 } 78 } 79 fclose(fp); 80 } 81 return 0; 82 }