pinocchio  3.2.0
A fast and flexible implementation of Rigid Body Dynamics algorithms and their analytical derivatives
file-io.hpp
1 //
2 // Copyright (c) 2020 LAAS-CNRS
3 //
4 
5 // modified from https://gist.github.com/rudolfovich/f250900f1a833e715260a66c87369d15
6 
7 #ifndef __pinocchio_utils_file_io_hpp__
8 #define __pinocchio_utils_file_io_hpp__
9 
10 #include <string>
11 #include <fstream>
12 #include <sstream>
13 
14 namespace pinocchio
15 {
16  class CsvStream
17  {
18  std::ofstream fs_;
19  bool is_first_;
20  const std::string separator_;
21  const std::string escape_seq_;
22  const std::string special_chars_;
23 
24  public:
25  CsvStream(const std::string filename, const std::string separator = ",")
26  : fs_()
27  , is_first_(true)
28  , separator_(separator)
29  , escape_seq_("\"")
30  , special_chars_("\"")
31  {
32  fs_.exceptions(std::ios::failbit | std::ios::badbit);
33  fs_.open(filename.c_str());
34  }
35 
36  ~CsvStream()
37  {
38  flush();
39  fs_.close();
40  }
41 
42  void flush()
43  {
44  fs_.flush();
45  }
46 
47  inline static CsvStream & endl(CsvStream & file)
48  {
49  file.endrow();
50  return file;
51  }
52 
53  void endrow()
54  {
55  fs_ << std::endl;
56  is_first_ = true;
57  }
58 
59  CsvStream & operator<<(CsvStream & (*val)(CsvStream &))
60  {
61  return val(*this);
62  }
63 
64  CsvStream & operator<<(const char * val)
65  {
66  return write(escape(val));
67  }
68 
69  CsvStream & operator<<(const std::string & val)
70  {
71  return write(escape(val));
72  }
73 
74  template<typename T>
75  CsvStream & operator<<(const T & val)
76  {
77  return write(val);
78  }
79 
80  private:
81  template<typename T>
82  CsvStream & write(const T & val)
83  {
84  if (!is_first_)
85  {
86  fs_ << separator_;
87  }
88  else
89  {
90  is_first_ = false;
91  }
92  fs_ << val;
93  return *this;
94  }
95 
96  std::string escape(const std::string & val)
97  {
98  std::ostringstream result;
99  result << '"';
100  std::string::size_type to, from = 0u, len = val.length();
101  while (from < len && std::string::npos != (to = val.find_first_of(special_chars_, from)))
102  {
103  result << val.substr(from, to - from) << escape_seq_ << val[to];
104  from = to + 1;
105  }
106  result << val.substr(from) << '"';
107  return result.str();
108  }
109  };
110 } // namespace pinocchio
111 
112 #endif
Main pinocchio namespace.
Definition: treeview.dox:11