tail(1p): trying from scratch

This commit is contained in:
Emma Tebibyte 2023-08-30 19:01:07 -06:00
parent e9effb5d43
commit 7936ce26a0
Signed by: emma
GPG Key ID: 6D661C738815E7DD

View File

@ -23,23 +23,11 @@
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "yac.h"
void tailc(FILE *file, long num) {
int byte;
char buf[num];
long offset = -num;
fseek(file, offset, SEEK_END);
for (int i = 0; (byte = fgetc(file)) != EOF; i++) {
buf[i] = byte;
}
fputs(buf, stdout);
}
void tailf(FILE *file) {
int byte;
@ -48,44 +36,6 @@ void tailf(FILE *file) {
}
}
void tailn(FILE *file, long num) {
char *buf = calloc(4096, 1);
char *lines[num];
int byte;
int lc = 0;
for (int bc = 0; (byte = fgetc(file)) != EOF; bc++) {
if (bc == sizeof(buf)) {
int err;
if (err = realloc(buf, sizeof(buf) * 2) == NULL) {
// TODO: error handling
}
}
buf[bc] = byte;
if (byte == '\n') {
lines[lc] = buf;
bc = 0;
lc++;
}
if (lc == num) {
for (int i = 0; i < lc; i++) {
lines[i] = lines[i + 1];
}
lc--;
}
}
int i;
if ((i = lc - num) < 0) { i = 0; }
for (; i < lc; i++) {
fputs(lines[i], stdout);
}
}
int main(int argc, char *argv[]) {
bool c = false;
bool f = false;
@ -140,13 +90,13 @@ int main(int argc, char *argv[]) {
case 'c':
c = true;
fn = tailc;
num = (long)optarg;
num = strtol(optarg, NULL, 10);
break;
case 'f':
f = true;
case 'n':
n = true;
num = (long)optarg;
num = strtol(optarg, NULL, 10);
break;
default:
fprintf(
@ -179,10 +129,10 @@ int main(int argc, char *argv[]) {
for (i = optind; i < argc; i++) {
if ((file = rpath(argv[0], argv[i])) != NULL) {
fn(file, num);
fclose(file);
}
if (f) { tailf(file); }
fclose(file);
}
}
return EX_OK;