1 /**
2 * dict.h
3 *
4 * Copyright (c) 1999, 2000, 2001
5 * Lu-chuan Kung and Kang-pen Chen.
6 * All rights reserved.
7 *
8 * Copyright (c) 2004
9 * libchewing Core Team. See ChangeLog for details.
10 *
11 * See the file "COPYING" for information on usage and redistribution
12 * of this file.
13 */
14
15 #include <stdio.h>
16 #include <assert.h>
17 #include <string.h>
18
19 #include "dict.h"
20
21 #include "private.h" // lukhnos
22
23 static int begin[ PHONE_PHRASE_NUM + 1 ];
24 static FILE *dictfile;
25 static int end_pos;
26
fgettab(char * buf,int maxlen,FILE * fp)27 char* fgettab( char *buf, int maxlen, FILE *fp )
28 {
29 int i;
30
31 for ( i = 0; i < maxlen; i++ ) {
32 buf[ i ] = (char) fgetc( fp );
33 if ( feof( fp ) )
34 break;
35 if ( buf[ i ] == '\t' )
36 break;
37 }
38 if ( feof( fp ) )
39 return 0;
40 buf[ i ] = '\0';
41 return buf;
42 }
43
TerminateDict()44 static void TerminateDict()
45 {
46 if ( dictfile )
47 fclose( dictfile );
48 }
49
InitDict(const char * prefix)50 int InitDict( const char *prefix )
51 {
52 FILE *indexfile;
53 int i;
54 char filename[ 100 ];
55
56 sprintf( filename, "%s/%s", prefix, DICT_FILE );
57 dictfile = fopen( filename, "r" );
58
59 sprintf( filename, "%s/%s", prefix, PH_INDEX_FILE );
60 indexfile = fopen( filename, "r" );
61 assert( dictfile && indexfile );
62 i = 0;
63 while ( !feof( indexfile ) )
64 fscanf( indexfile, "%d", &begin[ i++ ] );
65 fclose( indexfile );
66 addTerminateService( TerminateDict );
67 return 1;
68 }
69
Str2Phrase(Phrase * phr_ptr)70 void Str2Phrase( Phrase *phr_ptr )
71 {
72 char buf[ 1000 ];
73
74 fgettab( buf, 1000, dictfile );
75 sscanf( buf, "%s %d", phr_ptr->phrase, &( phr_ptr->freq ) );
76 }
77
GetPhraseFirst(Phrase * phr_ptr,int phone_phr_id)78 int GetPhraseFirst( Phrase *phr_ptr, int phone_phr_id )
79 {
80 assert( ( 0 <= phone_phr_id ) && ( phone_phr_id < PHONE_PHRASE_NUM ) );
81
82 fseek( dictfile, begin[ phone_phr_id ], SEEK_SET );
83 end_pos = begin[ phone_phr_id + 1 ];
84 Str2Phrase( phr_ptr );
85 return 1;
86 }
87
GetPhraseNext(Phrase * phr_ptr)88 int GetPhraseNext( Phrase *phr_ptr )
89 {
90 if ( ftell( dictfile ) >= end_pos )
91 return 0;
92 Str2Phrase( phr_ptr );
93 return 1;
94 }
95
96