root / tags / 1.0.8 / xapian-core / examples / simpleindex.cc

Revision 8874, 1.9 kB (checked in by olly, 19 months ago)

examples/simpleindex.cc: Tweak the logic to be clearer.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/** @file simpleindex.cc
2 * @brief Index each paragraph of a text file as a Xapian document.
3 */
4/* Copyright (C) 2007 Olly Betts
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19 */
20
21#include <xapian.h>
22
23#include <iostream>
24#include <string>
25
26#include <stdlib.h> // For exit().
27
28using namespace std;
29
30int
31main(int argc, char **argv)
32try {
33    if (argc != 2) {
34        cout << "Usage: " << argv[0] << " PATH_TO_DATABASE" << endl;
35        exit(1);
36    }
37
38    // Open the database for update, creating a new database if necessary.
39    Xapian::WritableDatabase db(argv[1], Xapian::DB_CREATE_OR_OPEN);
40
41    Xapian::TermGenerator indexer;
42    Xapian::Stem stemmer("english");
43    indexer.set_stemmer(stemmer);
44
45    string para;
46    while (true) {
47        string line;
48        if (cin.eof()) {
49            if (para.empty()) break;
50        } else {
51            getline(cin, line);
52        }
53
54        if (line.empty()) {
55            if (!para.empty()) {
56                // We've reached the end of a paragraph, so index it.
57                Xapian::Document doc;
58                doc.set_data(para);
59
60                indexer.set_document(doc);
61                indexer.index_text(para);
62
63                // Add the document to the database.
64                db.add_document(doc);
65
66                para = "";
67            }
68        } else {
69            if (!para.empty()) para += ' ';
70            para += line;
71        }
72    }
73} catch (const Xapian::Error &e) {
74    cout << e.get_description() << endl;
75    exit(1);
76}
Note: See TracBrowser for help on using the browser.