1

我有一个文本文件,用于保存其中出现的文件和单词(及其频率)的索引。我需要将文件读入内存并存储单词以便可以搜索它们。该文件的格式如下:

<files> 169
    0:file0.txt
    1:file1.txt
    2:file2.txt
    3:file3.txt
    ... etc ...
</files>
<list> word 2
    9: 10
    1: 2
</list>
<list> word2 4
    3: 19
    5: 12
    0: 2
    8: 2
</list>
... etc ...

问题是这个索引文件可能会变得非常大,并且不会一次全部放入内存中。我的解决方案是一次只将其中的几个存储在 HashTable 中,然后当我需要获取另一个单词的数据时,我会踢出一个旧单词,然后从文件中解析新单词的数据。

如何在 C 中有效地完成此任务?我在想,一旦我到达某些点,我就必须对 fseek 和倒带做一些事情。

谢谢,
迈克

4

3 回答 3

1

尽管 C 对字符串的支持很差——从我可以看出的样本来看,它有一个独特的模式,从磁盘重新解析它是可行的。

但是,我会考虑将文件转换为数据库并从那里开始工作。除非有理由不这样做,否则请使用第三方数据库引擎。

如果您决定重新解析文本文件,它看起来并不太难。首先将每个列表的起始位置存储为一对。然后你所做的就是寻找索引来读取特定单词的数据。

如果您的效率问题是计算机进行解析需要多长时间,请忘记它,找出对您来说最简单的方法。在你知道你需要之前不要优化。计算机既快速又便宜,而程序员则不然。

于 2011-05-05T03:13:06.380 回答
1

Like mattnz pointed out, this is best achieved using separate database layer. You can try SQlite. There is almost zero setup and is very stable. Otherwise, if you want to do this in C, you can have a header in beginning of file with links/indexes to each section of the file. Section being <files>..</files>, <list>..</list>. This is just on top of my head. If you read any book on implementing databases, you can find many more techniques.

于 2011-05-05T06:29:14.317 回答
0

It ended up that the best way to do this (for my needs) was to keep a pointer to current location in the file and the use rewind( FILE *f ); when I reached the end.

于 2011-05-13T16:28:53.090 回答