Rename from yp2 to metaproxy. The namespace for all definitions
[metaproxy-moved-to-github.git] / src / plainfile.cpp
1 /* $Id: plainfile.cpp,v 1.2 2006-03-16 10:40:59 adam Exp $
2    Copyright (c) 2005-2006, Index Data.
3
4 %LICENSE%
5  */
6
7 #include "config.hpp"
8
9 #include <cstdlib>
10 #include <string>
11 #include <iostream>
12 #include <fstream>
13
14 #include "util.hpp"
15
16 #define PLAINFILE_MAX_LINE 256
17
18 namespace mp = metaproxy_1;
19
20 namespace metaproxy_1 {
21     class PlainFile::Rep {
22         friend class PlainFile;
23         Rep();
24         void close();
25         int lineno;
26         std::ifstream *fh;
27     };
28 }
29
30 mp::PlainFile::Rep::Rep() : lineno(1)
31 {
32     fh = 0;
33 }
34
35 mp::PlainFile::PlainFile() : m_p(new Rep)
36 {
37 }
38
39 void mp::PlainFile::Rep::close()
40 {
41     delete fh;
42     fh = 0;
43     lineno = 0;
44 }
45
46 mp::PlainFile::~PlainFile()
47 {
48     m_p->close();
49 }
50
51 bool mp::PlainFile::open(const std::string &fname)
52 {
53     m_p->close();
54
55     std::ifstream *new_file = new std::ifstream(fname.c_str());
56     if (! *new_file)
57     {
58         delete new_file;
59         return false;
60     }
61     m_p->fh = new_file;
62     return true;
63 }
64
65 bool mp::PlainFile::getline(std::vector<std::string> &args)
66 {
67     args.clear();
68
69     if (!m_p->fh)
70         return false;  // no file at all.
71
72     char line_cstr[PLAINFILE_MAX_LINE];
73     while (true)
74     {
75         if (m_p->fh->eof())
76         {
77             m_p->close();   // might as well close it now
78             return false;
79         }
80         
81         m_p->lineno++;
82         m_p->fh->getline(line_cstr, PLAINFILE_MAX_LINE-1);
83         char first = line_cstr[0];
84         if (first && !strchr("# \t", first))
85             break;
86         // comment or blank line.. read next.
87     }
88     const char *cp = line_cstr;
89     while (true)
90     {
91         // skip whitespace
92         while (*cp && strchr(" \t", *cp))
93             cp++;
94         if (*cp == '\0')
95             break;
96         const char *cp0 = cp;
97         while (*cp && !strchr(" \t", *cp))
98             cp++;
99         std::string arg(cp0, cp - cp0);
100         args.push_back(arg);
101     }
102     return true;
103 }
104
105 /*
106  * Local variables:
107  * c-basic-offset: 4
108  * indent-tabs-mode: nil
109  * c-file-style: "stroustrup"
110  * End:
111  * vim: shiftwidth=4 tabstop=8 expandtab
112  */