From 206e7fb0c43332dd1fd2b51f437656deeae8e598 Mon Sep 17 00:00:00 2001
From: Paul Best <paulobest25@gmail.com>
Date: Tue, 17 Sep 2019 15:29:39 +0200
Subject: [PATCH] Incude milliseconds in filename (all OS compatible)

---
 src/filewriter.cpp | 21 +++++++++++++++++----
 src/main.cpp       |  2 +-
 2 files changed, 18 insertions(+), 5 deletions(-)

diff --git a/src/filewriter.cpp b/src/filewriter.cpp
index 89abc81..a86db05 100644
--- a/src/filewriter.cpp
+++ b/src/filewriter.cpp
@@ -8,7 +8,9 @@
 #include <stdexcept>
 #include <vector>
 #include <iostream>
-#include <ctime>
+#include <chrono>
+#include <sstream>
+#include <iomanip>
 
 FileWriter::FileWriter(std::string &filename_template, size_t num_channels, size_t sample_rate) :
         filename_template(filename_template), num_channels(num_channels), sample_rate(sample_rate) {
@@ -22,9 +24,20 @@ FileWriter::~FileWriter() {
 std::string FileWriter::generate_filename() {
     // this has of course nothing to do with file writing and could be pulled
     // out, but I doubt anybody will ever care
-    time_t timer;
-    time(&timer);
-    struct tm *timeinfo = localtime(&timer);
+    using namespace std::chrono;
+    auto miliseconds = duration_cast<milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
+    long seconds = miliseconds/1000;
+    struct tm *timeinfo = localtime(&seconds);
+
+    size_t found = filename_template.find("%z");
+    while(found != std::string::npos){
+      std::stringstream ss;
+      ss << std::setw(3) << std::setfill('0') << miliseconds%1000;
+      std::string s = ss.str();
+      filename_template.replace(found, 2, s);
+      found = filename_template.find("%z", found+3);
+    }
+
     size_t length = 0;
     size_t space = 0;
     std::vector<char> buffer;
diff --git a/src/main.cpp b/src/main.cpp
index 3e6e06b..8adee38 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -20,7 +20,7 @@ void print_usage(char *name) {
     std::cout << "  CHANNELS: number of channels to record (1 to 5)" << std::endl;
     std::cout << "  RATE: sample rate in Hz to record at (integral number)" << std::endl;
     std::cout << "  FILENAME: output file name; should include strftime() format specifiers" << std::endl;
-    std::cout << "    if CHUNKLEN is specified. Example: location/recording_%Y%m%dT%H%M%S.wav" << std::endl;
+    std::cout << "    if CHUNKLEN is specified. For miliseconds, use %z. Example: location/recording_%Y%m%dT%H%M%S%z.wav" << std::endl;
     std::cout << "  CHUNKLEN: length per output file in seconds; will start a new file whenever" << std::endl;
     std::cout << "    this length is reached. If not given or zero, will record a single file." << std::endl;
     std::cout << "  TOTALLEN: total recording length; will stop when this length is reached." << std::endl;
-- 
GitLab