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