Add a refer book
[fse.git] / query.c
blobe438128fa80f7de8041b5154ea771b102eac1b85
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <unistd.h>
8 #include "hash_index.h"
12 #define SETCOLOR_GREEN "\033[1;32m"
13 #define SETCOLOR_RED "\033[1;31m"
14 #define SETCOLOR_NORMAL "\033[0;39m"
17 void print_green(char c)
20 printf("%s%c%s", SETCOLOR_GREEN, c, SETCOLOR_NORMAL);
25 static char *get_file(char *keyword)
27 static char hash_file[512] = HASH_DIR;
29 sprintf(hash_file + HASH_DIR_LEN, "%02x/", do_hash(keyword));
30 strcat(hash_file, keyword);
31 return hash_file;
34 static void print_3_line(char *data, char *word, uint32_t file_pos)
36 char buf[1024];
37 char *p = data + file_pos;
38 char *q = buf;
39 int on = 2;
41 while (on) {
42 if (*p == '\n')
43 on--;
44 if (p <= data)
45 break;
46 p--;
48 p += 2;
49 on = 3;
50 while (on) {
51 if (*p == '\n')
52 on--;
53 *q++ = *p++;
55 *q = '\0';
57 q = buf;
58 while (*p) {
59 p = strstr(q, word);
60 if (!p) {
61 printf("%s", q);
62 break;
64 for (*q; q < p; q++)
65 printf("%c", *q);
66 p += strlen(word);
67 for (*q; q < p; q++)
68 print_green(*q);
73 * Query the keywords!
75 * count: is the keywords count.
76 * keywords: The address of the keywords strings.
78 static void query(int count, char *keywords[])
80 char buf[0x100000];
81 char *key;
82 char *hash_file;
83 int i;
84 int fd1, fd2;
85 struct key_words kw;
87 for (i = 0; i < count; i++) {
88 key = keywords[i];
89 hash_file = get_file(key);
90 fd1 = open(hash_file, O_RDONLY);
91 if (fd1 < 0)
92 continue;
93 while(read(fd1, &kw, sizeof kw) > 0) {
94 fd2 = open(kw.file, O_RDONLY);
95 if (fd2 < 0) {
96 printf("Open file %s error!\n", kw.file);
97 continue;
99 read(fd2, buf, sizeof buf);
100 print_3_line(buf, key, kw.file_pos);
101 printf("FROM file: %s\n\n", kw.file);
102 close(fd2);
104 close(fd1);
112 static void usage(void)
114 printf("USAGE: query keywords ....\n");
118 int main(int argc, char *argv[])
120 if (argc < 2) {
121 usage();
122 exit(0);
125 query(argc - 1, &argv[1]);
127 return 0;