GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: include/crocoddyl/core/utils/file-io.hpp Lines: 0 35 0.0 %
Date: 2024-02-13 11:12:33 Branches: 0 44 0.0 %

Line Branch Exec Source
1
///////////////////////////////////////////////////////////////////////////////
2
// BSD 3-Clause License
3
//
4
// Copyright (C) 2020 LAAS-CNRS
5
// Copyright note valid unless otherwise stated in individual files.
6
// All rights reserved.
7
///////////////////////////////////////////////////////////////////////////////
8
9
// modified from
10
// https://gist.github.com/rudolfovich/f250900f1a833e715260a66c87369d15
11
12
#ifndef CROCODDYL_CORE_UTILS_FILE_IO_HPP_
13
#define CROCODDYL_CORE_UTILS_FILE_IO_HPP_
14
15
#include <fstream>
16
#include <sstream>
17
#include <string>
18
19
class CsvStream {
20
  std::ofstream fs_;
21
  bool is_first_;
22
  const std::string separator_;
23
  const std::string escape_seq_;
24
  const std::string special_chars_;
25
26
 public:
27
  CsvStream(const std::string filename, const std::string separator = ",")
28
      : fs_(),
29
        is_first_(true),
30
        separator_(separator),
31
        escape_seq_("\""),
32
        special_chars_("\"") {
33
    fs_.exceptions(std::ios::failbit | std::ios::badbit);
34
    fs_.open(filename.c_str());
35
  }
36
37
  ~CsvStream() {
38
    flush();
39
    fs_.close();
40
  }
41
42
  void flush() { fs_.flush(); }
43
44
  inline static CsvStream& endl(CsvStream& file) {
45
    file.endrow();
46
    return file;
47
  }
48
49
  void endrow() {
50
    fs_ << std::endl;
51
    is_first_ = true;
52
  }
53
54
  CsvStream& operator<<(CsvStream& (*val)(CsvStream&)) { return val(*this); }
55
56
  CsvStream& operator<<(const char* val) { return write(escape(val)); }
57
58
  CsvStream& operator<<(const std::string& val) { return write(escape(val)); }
59
60
  template <typename T>
61
  CsvStream& operator<<(const T& val) {
62
    return write(val);
63
  }
64
65
 private:
66
  template <typename T>
67
  CsvStream& write(const T& val) {
68
    if (!is_first_) {
69
      fs_ << separator_;
70
    } else {
71
      is_first_ = false;
72
    }
73
    fs_ << val;
74
    return *this;
75
  }
76
77
  std::string escape(const std::string& val) {
78
    std::ostringstream result;
79
    result << '"';
80
    std::string::size_type to, from = 0u, len = val.length();
81
    while (from < len && std::string::npos !=
82
                             (to = val.find_first_of(special_chars_, from))) {
83
      result << val.substr(from, to - from) << escape_seq_ << val[to];
84
      from = to + 1;
85
    }
86
    result << val.substr(from) << '"';
87
    return result.str();
88
  }
89
};
90
91
#endif  // CROCODDYL_CORE_UTILS_FILE_IO_HPP_