-
Notifications
You must be signed in to change notification settings - Fork 0
/
dict.cpp
142 lines (113 loc) · 1.93 KB
/
dict.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// rspell
// (c) Copyright 2003, Recursive Pizza
// Ported to Windows, 2009
#include <stdio.h>
#include <ctype.h>
#include <sys/stat.h>
#include <map>
#include <string.h>
#include <string>
#include "rspell.h"
#include "dict.h"
#ifdef _WIN32
#include "windows.h"
#else
// Linux
static const char *main_dict = "/usr/share/dict/words";
#endif
typedef std::map<std::string, bool> DICT;
#ifdef _MSC_VER
#pragma warning(disable: 4996) // stdlib
#endif
static DICT dict;
inline void ToLower(char *s)
{
char *p;
for (p = s; *p; p++)
{
*p = tolower(*p);
}
}
static bool LoadDict(const char *file)
{
FILE *f;
char buf[MAX_WORD];
if ((f = fopen(file, "rt")) == NULL)
{
fprintf(stderr, "Could not open %s\n", file);
return false;
}
for (;;)
{
if (fgets(buf, sizeof(buf), f) == NULL) break;
Chomp(buf);
ToLower(buf);
dict[buf] = true;
}
fclose(f);
return true;
}
static bool IsExists(const char *file)
{
struct stat sb;
return stat(file, &sb) == 0;
}
static void LoadDict()
{
char buf[MAX_PATH] = "";
#ifdef _WIN32
// Windows
LPSTR p;
GetModuleFileName(NULL, buf, sizeof(buf));
if ((p = strrchr(buf, '\\')) == NULL)
{
p = &buf[lstrlen(buf) - 1]; // Last char
}
lstrcpyn(p + 1, "words.txt", sizeof(buf));
if (IsExists(buf))
{
LoadDict(buf);
}
#else
// Unix
LoadDict(main_dict);
snprintf(buf, sizeof(buf), "%s/words", getenv("HOME"));
if (IsExists(buf))
{
LoadDict(buf);
}
if (IsExists("words"))
{
LoadDict("words");
}
#endif
}
inline bool IsNumberChar(const char c)
{
return isdigit(c) || c == '.';
}
inline bool IsNumber(const char *s)
{
const char *p;
for (p = s; *p; p++)
{
if (!IsNumberChar(*p)) return false;
}
return true;
}
bool InDict(const char *word)
{
char lower[MAX_WORD];
if (dict.size() == 0)
{
LoadDict();
}
if (IsNumber(word)) return true;
#ifdef _MSC_VER
lstrcpyn(lower, word, sizeof(lower));
#else
strcpy(lower, word);
#endif
ToLower(lower);
return dict[lower];
}