commit d6a9e35d0bafd692d2957d01f5068e3bef6e24fc
parent 47308190b37e6e235f1a5581b215d13390af9914
Author: Connor Lane Smith <cls@lubutu.com>
Date: Wed, 25 May 2011 20:40:47 +0100
really long lines
Diffstat:
5 files changed, 52 insertions(+), 14 deletions(-)
diff --git a/Makefile b/Makefile
@@ -1,6 +1,6 @@
include config.mk
-LIB = util/enmasse.o util/eprintf.o util/recurse.o
+LIB = util/afgets.o util/enmasse.o util/eprintf.o util/recurse.o
SRC = basename.c cat.c chown.c date.c dirname.c echo.c false.c grep.c head.c \
ln.c mkfifo.c pwd.c rm.c sleep.c tee.c touch.c true.c wc.c
OBJ = $(SRC:.c=.o) $(LIB)
@@ -11,6 +11,7 @@ all: $(BIN)
$(OBJ): util.h
$(BIN): util.a
+grep: text.h
.o:
@echo CC -o $@
diff --git a/grep.c b/grep.c
@@ -4,6 +4,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
+#include "text.h"
static void grep(FILE *, const char *, regex_t *);
@@ -66,34 +67,39 @@ main(int argc, char *argv[])
void
grep(FILE *fp, const char *str, regex_t *preg)
{
- char buf[BUFSIZ];
- int n, c = 0;
+ char *buf = NULL;
+ long n, c = 0;
+ size_t size = 0;
- for(n = 1; fgets(buf, sizeof buf, fp); n++) {
+ for(n = 1; afgets(&buf, &size, fp); n++) {
if(regexec(preg, buf, 0, NULL, 0) ^ vflag)
continue;
- if(mode == 'c')
+ switch(mode) {
+ case 'c':
c++;
- else if(mode == 'l') {
- puts(str);
break;
- }
- else if(mode == 'q')
+ case 'l':
+ puts(str);
+ goto end;
+ case 'q':
exit(0);
- else {
+ default:
if(many)
printf("%s:", str);
if(mode == 'n')
- printf("%d:", n);
+ printf("%ld:", n);
fputs(buf, stdout);
+ break;
}
match = true;
}
if(mode == 'c')
- printf("%d\n", c);
+ printf("%ld\n", c);
+end:
if(ferror(fp)) {
fprintf(stderr, "%s: read error: ", str);
perror(NULL);
exit(2);
}
+ free(buf);
}
diff --git a/head.c b/head.c
@@ -1,6 +1,7 @@
/* See LICENSE file for copyright and license details. */
#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
#include <unistd.h>
#include "util.h"
@@ -38,10 +39,13 @@ void
head(FILE *fp, const char *str, long n)
{
char buf[BUFSIZ];
- long i;
+ long i = 0;
- for(i = 0; i < n && fgets(buf, sizeof buf, fp); i++)
+ while(i < n && fgets(buf, sizeof buf, fp)) {
fputs(buf, stdout);
+ if(buf[strlen(buf)-1] == '\n')
+ i++;
+ }
if(ferror(fp))
eprintf("%s: read error:", str);
}
diff --git a/text.h b/text.h
@@ -0,0 +1,3 @@
+/* See LICENSE file for copyright and license details. */
+
+char *afgets(char **p, size_t *size, FILE *fp);
diff --git a/util/afgets.c b/util/afgets.c
@@ -0,0 +1,24 @@
+/* See LICENSE file for copyright and license details. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../text.h"
+#include "../util.h"
+
+char *
+afgets(char **p, size_t *size, FILE *fp)
+{
+ char buf[BUFSIZ];
+ size_t n, len = 0;
+
+ while(fgets(buf, sizeof buf, fp)) {
+ len += (n = strlen(buf));
+ if(len+1 > *size && !(*p = realloc(*p, len+1)))
+ eprintf("realloc:");
+ strcpy(&(*p)[len-n], buf);
+
+ if(buf[n-1] == '\n' || feof(fp))
+ break;
+ }
+ return *p;
+}