utils

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

head.c (1743B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <unistd.h>
      4 
      5 int stoi_mini(char * str);
      6 
      7 int main(int argc, char *argv[]) {
      8   FILE * current_input_file;
      9   int i = 1, j = 0; char c;
     10 
     11   int chars_copy = 10;
     12   int print_head = 0;
     13 
     14   int error_occurred;
     15 
     16   
     17   if(argv[i][0] == '-') {
     18     if(argv[i][1] == 'n') {
     19       i++;
     20       chars_copy = stoi_mini(argv[i]);
     21       i++;
     22     }
     23   }
     24 
     25   if(argc - i > 1) {
     26     print_head = 1;
     27   }
     28 
     29   for(i; i < argc; i++) {
     30     if(argv[i][0] == '-' && argv[i][1] == '\0') {
     31       current_input_file = stdin;
     32     }
     33     else {
     34       current_input_file = fopen(argv[i], "r");
     35       if(current_input_file == NULL) {
     36 	fprintf(stderr, "%s: %s: No such file or directory\n",
     37 		argv[0], argv[i]);
     38 	error_occurred = 1;
     39       }
     40     }
     41     if(print_head) {
     42       printf("\n==> %s <==\n", argv[i]);
     43     }
     44     j = 0;
     45     c = ' ';
     46     while(c != EOF && j < chars_copy) {
     47       c = fgetc(current_input_file);
     48       if(c == '\n') {
     49 	j++;
     50       }
     51       if(c != EOF) {
     52 	fprintf(stdout, "%c", c);
     53       }
     54     }
     55     if(current_input_file != stdin) {
     56       fclose(current_input_file);
     57     }
     58   }
     59 
     60   if(error_occurred) {
     61     return 1;
     62   }
     63   else {
     64     return 0;
     65   }
     66 }
     67 
     68 int stoi_mini(char * str) {
     69   int i, str_int = 0;
     70 
     71   for(i = 0; str[i] != '\0' && str[i] != ','; i++) {
     72     str_int *= 10;
     73     switch(str[i]) {
     74       case '0': str_int += 0; break;
     75       case '1': str_int += 1; break;
     76       case '2': str_int += 2; break;
     77       case '3': str_int += 3; break;
     78       case '4': str_int += 4; break;
     79       case '5': str_int += 5; break;
     80       case '6': str_int += 6; break;
     81       case '7': str_int += 7; break;
     82       case '8': str_int += 8; break;
     83       case '9': str_int += 9; break;
     84       default: return -1;
     85     }
     86   }
     87 
     88   return str_int;
     89 }