FENIX_coreutils/head.c

90 lines
1.7 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int stoi_mini(char * str);
int main(int argc, char *argv[]) {
FILE * current_input_file;
int i = 1, j = 0; char c;
int chars_copy = 10;
int print_head = 0;
int error_occurred;
if(argv[i][0] == '-') {
if(argv[i][1] == 'n') {
i++;
chars_copy = stoi_mini(argv[i]);
i++;
}
}
if(argc - i > 1) {
print_head = 1;
}
for(i; i < argc; i++) {
if(argv[i][0] == '-' && argv[i][1] == '\0') {
current_input_file = stdin;
}
else {
current_input_file = fopen(argv[i], "r");
if(current_input_file == NULL) {
fprintf(stderr, "%s: %s: No such file or directory\n",
argv[0], argv[i]);
error_occurred = 1;
}
}
if(print_head) {
printf("\n==> %s <==\n", argv[i]);
}
j = 0;
c = ' ';
while(c != EOF && j < chars_copy) {
c = fgetc(current_input_file);
if(c == '\n') {
j++;
}
if(c != EOF) {
fprintf(stdout, "%c", c);
}
}
if(current_input_file != stdin) {
fclose(current_input_file);
}
}
if(error_occurred) {
return 1;
}
else {
return 0;
}
}
int stoi_mini(char * str) {
int i, str_int = 0;
for(i = 0; str[i] != '\0' && str[i] != ','; i++) {
str_int *= 10;
switch(str[i]) {
case '0': str_int += 0; break;
case '1': str_int += 1; break;
case '2': str_int += 2; break;
case '3': str_int += 3; break;
case '4': str_int += 4; break;
case '5': str_int += 5; break;
case '6': str_int += 6; break;
case '7': str_int += 7; break;
case '8': str_int += 8; break;
case '9': str_int += 9; break;
default: return -1;
}
}
return str_int;
}