really long lines

This commit is contained in:
Connor Lane Smith 2011-05-25 20:40:47 +01:00
parent 47308190b3
commit d6a9e35d0b
5 changed files with 52 additions and 14 deletions

View File

@ -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 $@

28
grep.c
View File

@ -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);
}

8
head.c
View File

@ -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);
}

3
text.h Normal file
View File

@ -0,0 +1,3 @@
/* See LICENSE file for copyright and license details. */
char *afgets(char **p, size_t *size, FILE *fp);

24
util/afgets.c Normal file
View File

@ -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;
}