FENIX_coreutils/head.c
2020-12-13 10:09:04 -06:00

65 lines
No EOL
1.1 KiB
C
Executable file

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
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;
while((c = getopt(argc, argv, "n:")) != -1) {
if(c == 'n') {
chars_copy = atoi(optarg);
}
}
i = optind;
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;
}
}