def peek(st, ps, es, toks): s = ps while s < es and strchr(WHITESPACE, st[s]): s += 1 ps = s return (st[s] != "\0") and (strchr(toks, st[s]) != 0), ps
def gettoken(st, ps, es): s = ps while s < es and strchr(WHITESPACE, st[s]): s += 1 q = s ret = st[s] if st[s] == "\0": # @@@ can this happen? pass elif st[s] in "|();&<": s += 1 elif st[s] == ">": s += 1 if st[s] == ">": ret = "+" s += 1 else: ret = "a" while s < es and not strchr(WHITESPACE, st[s]) and not strchr(SYMBOLS, st[s]): s += 1 eq = s while s < es and strchr(WHITESPACE, st[s]): s += 1 ps = s return ret, ps, q, eq
def grep(pattern, fd): m = 0 buf = " " * 1024 # while (n = read(fd, buf+m, sizeof(buf)-m)) > 0 while True: n, s = read(fd, 1024 - m) buf = buf[:m] + s if n <= 0: break m += n p = buf # while (q = strchr(p, '\n')) != 0 while True: q = strchr(p, "\n") if q == 0: break q = "\0" + q[1:] if match(pattern, p): q = "\n" + q[1:] write(1, p, len(p) + 1 - len(q)) p = q[1:] if p == buf: m = 0 if m > 0: m -= len(p) - len(buf) # memmove(buf, p, m) buf = p[:m] + buf[m:]
def wc(fd, name): l = 0 w = 0 c = 0 inword = False # while((n = read(fd, buf, sizeof(buf))) > 0) while True: n, buf = read(fd, 512) if n <= 0: break for i in range(n): c += 1 if buf[i] == "\n": l += 1 if strchr(" \r\t\n\v", buf[i]): inword = False elif not inword: w += 1 inword = True if n < 0: printf(1, "wc: read error\n") exit_(1) printf(1, "%d %d %d %s\n", l, w, c, name)