1 #include "gcin.h"
2 #include "gtab.h"
3
4 typedef struct {
5 int use_count;
6 u_char bytes, flag;
7 } GTAB_USE_CNT;
8
9 static char gtab_use_count_file[]="gtab-use-count2";
10 static FILE *fp_gtab_use_count;
11
init_fp()12 static void init_fp()
13 {
14 if (!fp_gtab_use_count) {
15 char fname[128];
16 get_gcin_user_fname(gtab_use_count_file, fname);
17
18 if (!(fp_gtab_use_count=fopen(fname, "rb+"))) {
19 if (!(fp_gtab_use_count=fopen(fname, "wb+"))) {
20 dbg("cannot write to %s\n", fname);
21 return;
22 }
23 }
24 }
25 }
26
close_gtab_use_count()27 void close_gtab_use_count() {
28 if (!fp_gtab_use_count)
29 return;
30 fclose(fp_gtab_use_count);
31 }
32
inc_gtab_use_count(char * s)33 void inc_gtab_use_count(char *s)
34 {
35 init_fp();
36
37 int bytes = strlen(s);
38
39 GTAB_USE_CNT c;
40 rewind(fp_gtab_use_count);
41
42 // dbg("zzz '%s' bytes:%d\n", s, bytes);
43 // dbg("inc %d\n", ftell(fp_gtab_use_count));
44 while (!feof(fp_gtab_use_count)) {
45 char tt[512];
46 bzero(&c, sizeof(c));
47 fread(&c, sizeof(c), 1, fp_gtab_use_count);
48 if (c.bytes != bytes)
49 continue;
50 fread(tt, bytes, 1, fp_gtab_use_count);
51
52 if (memcmp(tt, s, bytes))
53 continue;
54
55 long ofs = ftell(fp_gtab_use_count);
56 // dbg("aa %d ofs:%d sz:%d\n", c.use_count, ofs, sizeof(c));
57 fseek(fp_gtab_use_count, - (sizeof(c)+bytes) , SEEK_CUR);
58 // dbg("bb %d ofs:%d\n", c.use_count, ftell(fp_gtab_use_count));
59
60 c.use_count++;
61 fwrite(&c, sizeof(c), 1, fp_gtab_use_count);
62 fflush(fp_gtab_use_count);
63 return;
64 }
65
66 int fofs = ftell(fp_gtab_use_count);
67 // dbg("fofs: %d\n", fofs);
68
69 #if 0
70 int delta = fofs % sizeof(GTAB_USE_CNT);
71 if (delta) // avoid incomplete write
72 fseek(fp_gtab_use_count, - delta, SEEK_CUR);
73 #endif
74
75 bzero(&c, sizeof(c));
76 c.use_count = 1;
77 c.bytes = bytes;
78 fwrite(&c, sizeof(c), 1, fp_gtab_use_count);
79 fwrite(s, bytes, 1, fp_gtab_use_count);
80 fflush(fp_gtab_use_count);
81 }
82
83
get_gtab_use_count(char * s)84 int get_gtab_use_count(char *s)
85 {
86 int bytes = strlen(s);
87 init_fp();
88
89 // dbg("get_gtab_use_count %s\n", s);
90
91 GTAB_USE_CNT c;
92 rewind(fp_gtab_use_count);
93 while (!feof(fp_gtab_use_count)) {
94 fread(&c, sizeof(c), 1, fp_gtab_use_count);
95 if (c.bytes != bytes)
96 continue;
97 char tt[512];
98 fread(tt, bytes, 1, fp_gtab_use_count);
99
100 if (!memcmp(tt, s, bytes)) {
101 // dbg("count found %s %d\n", s, c.use_count);
102 return c.use_count;
103 }
104 }
105
106 // dbg("not found\n");
107
108 return 0;
109 }
110