simple_io.cpp
1 #include "simple_io.hpp"
2 #include "universal_error.hpp"
3 #include <cassert>
4 
5 void write_number(double num,
6  string const& fname,
7  int prec)
8 {
9  ofstream f(fname.c_str());
10  f.precision(prec);
11  f << num << endl;
12  f.close();
13 }
14 
15 void write_vector(vector<double> const& v,
16  string const& fname,
17  int prec)
18 {
19  ofstream f(fname.c_str());
20  f.precision(prec);
21  for(size_t i=0;i<v.size();++i)
22  f << v[i] << "\n";
23  f.close();
24 }
25 
26 void write_vector(vector<int> const& v,
27  string const& fname)
28 {
29  ofstream f(fname.c_str());
30  for(size_t i=0;i<v.size();++i)
31  f << v[i] << endl;
32  f.close();
33 }
34 
35 namespace {
36  bool missing_file_data(string const& fname)
37  {
38  std::cout << "Could not find file " << fname << std::endl;
39  return false;
40  }
41 }
42 
43 vector<double> read_vector(string const& fname)
44 {
45  double buf = 0;
46  vector<double> res;
47  ifstream f(fname.c_str());
48  assert(f || missing_file_data(fname));
49  while (f >> buf)
50  res.push_back(buf);
51  f.close();
52  return res;
53 }
54 
55 double read_number(string const& fname)
56 {
57  double buf = 0;
58  ifstream f(fname.c_str());
59  assert(f || missing_file_data(fname));
60  f >> buf;
61  f.close();
62  return buf;
63 }
64 
65 int read_int(string const& fname)
66 {
67  int buf = 0;
68  ifstream f(fname.c_str());
69  assert(f || missing_file_data(fname));
70  f >> buf;
71  f.close();
72  return buf;
73 }
74 
75 void binary_write_single_int(int n, ofstream& fh)
76 {
77  fh.write(reinterpret_cast<const char*>(&n),sizeof(int));
78 }
79 
80 void binary_write_single_double(double d, ofstream& fh)
81 {
82  fh.write(reinterpret_cast<const char*>(&d),sizeof(double));
83 }
84 
85 void binary_write_single_size_t(size_t n,ofstream& fh)
86 {
87  fh.write(reinterpret_cast<const char*>(&n),sizeof(size_t));
88 }
int read_int(string const &fname)
Reads a single integer from a file.
Definition: simple_io.cpp:65
void write_vector(vector< double > const &v, string const &fname, int prec=6)
Writes a list of numbers to a file.
Definition: simple_io.cpp:15
void binary_write_single_double(double d, ofstream &fh)
Writes a double to a binary file.
Definition: simple_io.cpp:80
vector< double > read_vector(string const &fname)
Reads a several numbers from a file.
Definition: simple_io.cpp:43
double read_number(string const &fname)
Reads a single number from a file.
Definition: simple_io.cpp:55
void binary_write_single_size_t(size_t n, ofstream &fh)
Writes a single size_t to a binary file.
Definition: simple_io.cpp:85
void binary_write_single_int(int n, ofstream &fh)
Writes a single integer to a binary file.
Definition: simple_io.cpp:75
A class for storing error and debug information.
A collection of simple input / output methods.
void write_number(double num, string const &fname, int prec=6)
Writes a single number to a file.
Definition: simple_io.cpp:5