file-io.hpp
Go to the documentation of this file.
1 #ifndef _parameteric_curves_utils_file_io_hpp
2 #define _parameteric_curves_utils_file_io_hpp
3 
4 #include <Eigen/Dense>
5 #include <fstream>
6 
7 #define MAXBUFSIZE ((int)1000000)
8 
9 namespace parametriccurves {
10 namespace utils {
11 
12 const Eigen::MatrixXd readMatrixFromFile(const std::string& filename) {
13  int cols = 0, rows = 0;
14  double buff[MAXBUFSIZE];
15 
16  // Read numbers from file into buffer.
17  std::ifstream infile;
18  infile.open(filename.c_str());
19  while (!infile.eof()) {
20  std::string line;
21  getline(infile, line);
22  // std::cout<<"Read line "<<rows<<"\n";
23 
24  int temp_cols = 0;
25  std::stringstream stream(line);
26  while (!stream.eof()) stream >> buff[cols * rows + temp_cols++];
27 
28  if (temp_cols == 0) continue;
29 
30  if (cols == 0)
31  cols = temp_cols;
32  else if (temp_cols != cols && !infile.eof()) {
33  std::cout << "Error while reading matrix from file, line " << rows
34  << " has " << temp_cols
35  << " columnds, while preceding lines had " << cols
36  << " columnds\n";
37  std::cout << line << "\n";
38  break;
39  }
40 
41  rows++;
42  if ((rows + 1) * cols >= MAXBUFSIZE) {
43  std::cout << "Max buffer size exceeded (" << rows << " rows, " << cols
44  << " cols)\n";
45  break;
46  }
47  }
48  infile.close();
49  rows--;
50 
51  // Populate matrix with numbers.
52  Eigen::MatrixXd result(rows, cols);
53  for (int i = 0; i < rows; i++)
54  for (int j = 0; j < cols; j++) result(i, j) = buff[cols * i + j];
55  return result;
56 }
57 
58 } // namespace utils
59 } // namespace parametriccurves
60 
61 #endif //_CLASS_EXACTCUBIC
#define MAXBUFSIZE
to read text file
Definition: file-io.hpp:7
const Eigen::MatrixXd readMatrixFromFile(const std::string &filename)
Definition: file-io.hpp:12
Definition: abstract-curve.hpp:16