#define MAX_LEN 64
#endif
+#ifndef BUF_LEN
+#define BUF_LEN (64*1024)
+#endif
+
typedef struct cs_t {
char buf[MAX_LEN];
size_t start; /* index of firs char */
} *cs;
+typedef struct buf_t {
+ char buf[BUF_LEN];
+
+ FILE *fp;
+ size_t cap /* max string size; <= MAX_LEN */ ;
+ size_t cur;
+} *buf;
+
static void cs_init(cs S, size_t cap);
static void cs_add(cs S, char ch);
static int cs_cmp(cs S, char *ch);
static void cs_print(cs S);
+static void buf_init(buf B, FILE *);
+static void buf_read(buf B);
+static char buf_next_ch(buf B);
+static int buf_eof(buf B);
+
int main(int argc, char **argv)
{
int ch = 0;
time_t now;
char str[MAX_LEN];
- struct cs_t matcher;
+ struct cs_t S;
+ struct buf_t B;
if (argc < 2) {
printf("Usage: %s <string to find>\n", argv[0]);
printf("Check against %s\n", str);
now = time(0);
- cs_init(&matcher, strlen(str));
+ buf_init(&B, stdin);
+ cs_init(&S, strlen(str));
+
+ for (n = 1;; ++n) {
+ ch = buf_next_ch(&B);
+ if (!ch && buf_eof(&B))
+ break;
- for (n = 1; (ch = fgetc(stdin)) != EOF; ++n) {
- cs_add(&matcher, ch);
+ cs_add(&S, ch);
- if (matcher.len == matcher.cap) {
- if (cs_cmp(&matcher, str)) {
- printf("Found at %llu\t%lu\n", n - matcher.cap, time(0) - now);
- /* cs_print(&matcher); printf("\n"); */
+ if (S.len == S.cap) {
+ if (cs_cmp(&S, str)) {
+ printf("Found at %llu\t%lu\n", n - S.cap, time(0) - now);
+ /* cs_print(&S); printf("\n"); */
}
}
}
++count;
}
}
+
+static void buf_init(buf B, FILE * fp)
+{
+ B->cap = 0;
+ B->cur = 0;
+ B->fp = fp;
+}
+
+static void buf_read(buf B)
+{
+ B->cap = fread(B->buf, 1, sizeof(B->buf), B->fp);
+ B->cur = 0;
+}
+
+static char buf_next_ch(buf B)
+{
+ if (B->cur >= B->cap) {
+ buf_read(B);
+ if (B->cap == 0)
+ return '\0';
+ }
+ return B->buf[B->cur++];
+}
+
+static int buf_eof(buf B)
+{
+ return feof(B->fp) && B->cur >= B->cap;
+}