Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /** Log to a CSV file on your host computer.
- * @example CsvLogger<10,3> logger;
- * while(true)
- * logger.append("/path/to/foo.csv", {1.1, 2.2, 3.3})
- * @tparam N_rows Buffer N_rows before writing to disk to minimize lag due to semi-hosting
- * @tparam N_cols Columns of your CSV*/
- template <unsigned int N_rows, unsigned int N_cols>
- class CsvLogger
- {
- public:
- void append(const char* path, const std::array<float, N_cols>& row)
- {
- _buffer.at(_row_index++) = row;
- bool buffer_is_full = (_row_index > N_rows-1);
- if (buffer_is_full)
- {
- _row_index =0;
- FILE* log_file = fopen(path, "a");
- for (const auto& row: _buffer)
- {
- for (float col: row)
- {
- // The CSV values
- fprintf(log_file, "%.4f,", col);
- }
- fprintf(log_file, "\n");
- }
- fclose(log_file);
- }
- }
- private:
- size_t _row_index{0};
- std::array<std::array<float, N_cols>, N_rows> _buffer;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement