metaproxy  1.13.0
plainfile.cpp
Go to the documentation of this file.
1 /* This file is part of Metaproxy.
2  Copyright (C) Index Data
3 
4 Metaproxy is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8 
9 Metaproxy is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 for more details.
13 
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18 
19 #include "config.hpp"
20 
21 #include <cstdlib>
22 #include <string>
23 #include <iostream>
24 #include <fstream>
25 
26 #include <metaproxy/util.hpp>
27 
28 #define PLAINFILE_MAX_LINE 256
29 
30 namespace mp = metaproxy_1;
31 
32 namespace metaproxy_1 {
34  friend class PlainFile;
35  Rep();
36  void close();
37  int lineno;
38  std::ifstream *fh;
39  };
40 }
41 
42 mp::PlainFile::Rep::Rep() : lineno(1)
43 {
44  fh = 0;
45 }
46 
47 mp::PlainFile::PlainFile() : m_p(new Rep)
48 {
49 }
50 
51 void mp::PlainFile::Rep::close()
52 {
53  delete fh;
54  fh = 0;
55  lineno = 0;
56 }
57 
58 mp::PlainFile::~PlainFile()
59 {
60  m_p->close();
61 }
62 
63 bool mp::PlainFile::open(const std::string &fname)
64 {
65  m_p->close();
66 
67  std::ifstream *new_file = new std::ifstream(fname.c_str());
68  if (! *new_file)
69  {
70  delete new_file;
71  return false;
72  }
73  m_p->fh = new_file;
74  return true;
75 }
76 
77 bool mp::PlainFile::getline(std::vector<std::string> &args)
78 {
79  args.clear();
80 
81  if (!m_p->fh)
82  return false; // no file at all.
83 
84  char line_cstr[PLAINFILE_MAX_LINE];
85  while (true)
86  {
87  if (m_p->fh->eof())
88  {
89  m_p->close(); // might as well close it now
90  return false;
91  }
92 
93  m_p->lineno++;
94  m_p->fh->getline(line_cstr, PLAINFILE_MAX_LINE-1);
95  char first = line_cstr[0];
96  if (first && !strchr("# \t", first))
97  break;
98  // comment or blank line.. read next.
99  }
100  const char *cp = line_cstr;
101  while (true)
102  {
103  // skip whitespace
104  while (*cp && strchr(" \t", *cp))
105  cp++;
106  if (*cp == '\0')
107  break;
108  const char *cp0 = cp;
109  while (*cp && !strchr(" \t", *cp))
110  cp++;
111  std::string arg(cp0, cp - cp0);
112  args.push_back(arg);
113  }
114  return true;
115 }
116 
117 /*
118  * Local variables:
119  * c-basic-offset: 4
120  * c-file-style: "Stroustrup"
121  * indent-tabs-mode: nil
122  * End:
123  * vim: shiftwidth=4 tabstop=8 expandtab
124  */
125 
#define PLAINFILE_MAX_LINE
Definition: plainfile.cpp:28