XGC1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
file_reader.hpp
Go to the documentation of this file.
1 #ifndef FILE_READER_HPP
2 #define FILE_READER_HPP
3 
4 #include <fstream>
5 
6 class FileReader{
7 
8  std::ifstream ifile;
9  std::string filename;
10 
11  public:
12 
13  void open(const std::string& input){
14  // Open file
15  ifile = std::ifstream(input, std::ios::in);
16 
17  // Check to see that the file was opened correctly:
18  if (!ifile.is_open()) {
19  std::cerr << "There was a problem opening the input file '" << input << "'.\n";
20  exit(1); // exit or do additional error checking
21  }
22 
23  filename = input;
24  }
25 
26  // Read an array from plain text file
27  template<typename T>
28  void read(T* var, int n){
29  int i = 0;
30  T num = 0;
31  // Store values from text file to array
32  while (i<n && ifile >> num) {
33  var[i] = num;
34  i++;
35  }
36 
37  // If there was insufficient data in the file to fill the array
38  if (i!=n){
39  std::cerr << "Error parsing file '" << filename << "': Reached end of file, but more data was expected!\n";
40  exit(1);
41  }
42  }
43 
44  // Skip some data
45  void skip(int n){
46  int i = 0;
47  int num = 0;
48 
49  // Read data but ignore it
50  while (i<n && ifile >> num) {
51  i++;
52  }
53 
54  // If there was insufficient data to skip n values
55  if (i!=n){
56  std::cerr << "Error parsing file '" << filename << "': Reached end of file, but more data was expected!\n";
57  exit(1);
58  }
59  }
60 
61  // Skip entire line
62  void skip_line(){
63  std::string line;
64  getline(ifile, line);
65  }
66 };
67 
68 #endif
void read(T *var, int n)
Definition: file_reader.hpp:28
std::ifstream ifile
Definition: file_reader.hpp:8
std::string filename
Definition: file_reader.hpp:9
Definition: file_reader.hpp:6
void skip_line()
Definition: file_reader.hpp:62
void skip(int n)
Definition: file_reader.hpp:45
void open(const std::string &input)
Definition: file_reader.hpp:13