Canoe
Comprehensive Atmosphere N' Ocean Engine
read_data_table.cpp
Go to the documentation of this file.
1 // C/C++ headers
2 #include <athena/athena_arrays.hpp>
3 #include <cassert>
4 #include <cstdio>
5 #include <sstream>
6 
7 #include "fileio.hpp"
8 #include "ndarrays.hpp"
9 
10 void read_data_table(char const *fname, double **data, int *rows, int *cols) {
11  FILE *fp = fopen(fname, "r");
12 
13  // read dimension of the table
14  fscanf(fp, "%d%d", rows, cols);
15 
16  NewCArray(data, *rows, *cols);
17 
18  char buf[256];
19  int irow = 0, icol;
20  char *p;
21  while (fgets(buf, 256, fp) != NULL) {
22  p = std::strtok(buf, " ,");
23  int icol = 0;
24  while (p != NULL) {
25  sscanf(p, "%lf", &data[irow][icol]);
26  p = std::strtok(NULL, " ,");
27  assert(icol++ < *cols);
28  }
29  assert(irow++ < *rows);
30  }
31 
32  fclose(fp);
33 }
34 
35 void ReadDataTable(AthenaArray<Real> *data, std::string fname, char c) {
36  // remove comment
37  std::string str_file = DecommentFile(fname);
38 
39  // read first time to determine dimension
40  std::stringstream inp(str_file);
41  // std::ifstream inp(fname.c_str(), std::ios::in);
42  std::string line;
43  std::getline(inp, line);
44  int rows = 0, cols = 0;
45  if (!line.empty()) {
46  rows = 1;
47  cols = line[0] == c ? 0 : 1;
48  for (int i = 1; i < line.length(); ++i)
49  if (line[i - 1] == c && line[i] != c) cols++;
50  }
51  while (std::getline(inp, line)) ++rows;
52  rows--;
53  // inp.close();
54 
55  // str_file = DecommentFile(fname);
56 
57  // read second time
58  data->NewAthenaArray(rows, cols);
59  std::stringstream inp2(str_file);
60  // inp.open(fname.c_str(), std::ios::in);
61 
62  for (int i = 0; i < rows; ++i)
63  for (int j = 0; j < cols; ++j) inp2 >> (*data)(i, j);
64 }
std::string DecommentFile(std::string fname)
decomment a file
Definition: fileio.cpp:30
void NewCArray(T **&a, int n1, int n2)
Definition: ndarrays.hpp:5
void ReadDataTable(AthenaArray< Real > *data, std::string fname, char c)
void read_data_table(char const *fname, double **data, int *rows, int *cols)