tail added

This commit is contained in:
Your Name 2024-10-01 10:46:16 +03:00
parent 0306c4319b
commit ea0004c11f
3 changed files with 29 additions and 9 deletions

1
TODO
View File

@ -52,3 +52,4 @@ FIX:
xargs (-d)
echo (escape)
que (unicode)
ps (-o)

View File

@ -1,5 +1,12 @@
#define _HEAD_C
#ifdef _TAIL_C
#define PROG_NAME "tail"
#else
#define PROG_NAME "head"
#define _TAIL_C 0
#endif
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
@ -16,10 +23,13 @@ static long parse_long(const char *str) {
char *ptr;
long ret = strtol(str, &ptr, 0);
if (*ptr) {
fprintf(stderr, "head: invalid number %s\n", ptr);
fprintf(stderr, "%s: invalid number %s\n", PROG_NAME, ptr);
exit(1);
}
if (_TAIL_C && ret < 0)
ret *= -1;
return ret;
}
@ -31,7 +41,7 @@ static int print(const char *file, FILE *fp, long lines, long bytes) {
long bcount = 0;
/* If lines or bytes < 0 */
if (lines < 0 || bytes < 0) {
if ((lines < 0 || bytes < 0) || _TAIL_C) {
long lmax = 0;
long bmax = 0;
@ -39,10 +49,11 @@ static int print(const char *file, FILE *fp, long lines, long bytes) {
size_t buf_size = 0;
char *buf = malloc(1);
if (buf == NULL) {
fprintf(stderr, "head: malloc: %s\n", strerror(errno));
fprintf(stderr, "%s: malloc: %s\n", PROG_NAME, strerror(errno));
return 1;
}
/* Fill buffer */
while (1) {
int c = getc(fp);
if (c == EOF)
@ -50,7 +61,7 @@ static int print(const char *file, FILE *fp, long lines, long bytes) {
char *tmp = realloc(buf, buf_size + 2);
if (tmp == NULL) {
fprintf(stderr, "head: realloc: %s\n", strerror(errno));
fprintf(stderr, "%s: realloc: %s\n", PROG_NAME, strerror(errno));
free(buf);
return 1;
@ -72,9 +83,15 @@ static int print(const char *file, FILE *fp, long lines, long bytes) {
lcount++;
bcount++;
putchar(buf[i]);
if ((n_flag && lcount == lmax + lines) || (c_flag && bcount == bmax + bytes))
break;
if ((c_flag && bmax - bcount < bytes) || (n_flag && lmax - lcount < lines))
putchar(buf[i]);
else if (!_TAIL_C) {
putchar(buf[i]);
if ((n_flag && lcount == lmax + lines) || (c_flag && bcount == bmax + bytes))
break;
}
}
free(buf);
@ -121,7 +138,7 @@ int main(int argc, char **argv) {
break;
default:
puts("head [ncv] [file1 file2...]\n\t-n Print [-]N lines\n\t-c Print [-]N bytes\n\t-v Print headers");
printf("%s [ncv] [file1 file2...]\n\t-n Print [-]N lines\n\t-c Print [-]N bytes\n\t-v Print headers\n", PROG_NAME);
return 0;
}
}
@ -142,7 +159,7 @@ int main(int argc, char **argv) {
fp = fopen(argv[i], "r");
if (fp == NULL) {
fprintf(stderr, "head: %s: %s\n", argv[i], strerror(errno));
fprintf(stderr, "%s: %s: %s\n", PROG_NAME, argv[i], strerror(errno));
ret = 1;
continue;

2
src/tail.c Normal file
View File

@ -0,0 +1,2 @@
#define _TAIL_C 1
#include "head.c"