forked from AMSC-24-25/amsc-24-25-classroom-20-fft-FFT
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcsv-signal-saver.cpp
48 lines (45 loc) · 1.74 KB
/
csv-signal-saver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "signal-saver/csv-signal-saver.hpp"
#include "utils/timestamp.hpp"
#include <chrono>
#include <filesystem>
#include <fstream>
void CsvSignalSaver::saveToFile(const std::vector<std::complex<double>> &signal, const std::string &filePath) const {
const std::string output_file_path = std::format(
"{}_{}.{}", filePath, createReadableTimestamp("%Y%m%d_%H%M%S"), getExtension()
);
printf("Saving signal to file: %s\n", output_file_path.c_str());
// validate the input
if (signal.empty()) {
throw std::invalid_argument("Signal cannot be empty");
}
if (filePath.empty()) {
throw std::invalid_argument("File path cannot be empty");
}
// ensure the parent directory exists
std::filesystem::path path(filePath);
if (path.has_extension()) {
throw std::invalid_argument("File path should not contain an extension: " + filePath);
}
create_directories(path.parent_path());
// check if the file already exists
if (std::filesystem::exists(output_file_path)) {
throw std::runtime_error("File already exists: " + output_file_path);
}
// define the file
std::ofstream file(output_file_path);
// check if the file was opened
if (!file.is_open()) {
throw std::runtime_error("Could not open file: " + output_file_path);
}
// write the signal to the file
for (const std::complex<double> &sample : signal) {
file << std::format("{},{}\n", sample.real(), sample.imag());
}
// close the file
file.close();
printf("Signal saved successfully to file: %s\n", output_file_path.c_str());
}
[[nodiscard]] const std::string &CsvSignalSaver::getExtension() const {
static const std::string extension = "csv";
return extension;
}