Guest User

Untitled

a guest
Mar 11th, 2021
30
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /** Log to a CSV file on your host computer.
  2.  * @example CsvLogger<10,3> logger;
  3.  *          while(true)
  4.  *               logger.append("/path/to/foo.csv", {1.1, 2.2, 3.3})
  5.  * @tparam N_rows Buffer N_rows before writing to disk to minimize lag due to semi-hosting
  6.  * @tparam N_cols Columns of your CSV*/
  7. template <unsigned int N_rows, unsigned int N_cols>
  8. class CsvLogger
  9. {
  10. public:
  11.     void append(const char* path, const std::array<float, N_cols>& row)
  12.     {
  13.         _buffer.at(_row_index++) = row;
  14.  
  15.         bool buffer_is_full = (_row_index > N_rows-1);
  16.         if (buffer_is_full)
  17.         {
  18.             _row_index =0;
  19.             FILE* log_file = fopen(path, "a");
  20.             for (const auto& row: _buffer)
  21.             {
  22.                 for (float col: row)
  23.                 {
  24.                     // The CSV values
  25.                     fprintf(log_file, "%.4f,", col);
  26.                 }
  27.                 fprintf(log_file, "\n");
  28.             }
  29.             fclose(log_file);
  30.         }
  31.     }
  32.  
  33. private:
  34.     size_t _row_index{0};
  35.     std::array<std::array<float, N_cols>, N_rows> _buffer;
  36. };
RAW Paste Data