]> git.lttng.org Git - lttng-tools.git/commitdiff
utils: Add generic helper to create value files
authorKienan Stewart <kstewart@efficios.com>
Mon, 25 Nov 2024 16:06:39 +0000 (11:06 -0500)
committerJérémie Galarneau <jeremie.galarneau@efficios.com>
Wed, 18 Dec 2024 15:53:24 +0000 (15:53 +0000)
Change-Id: Ie814a4ddd22d9af578a194b73ed52b65df5128e4
Signed-off-by: Kienan Stewart <kstewart@efficios.com>
Signed-off-by: Jérémie Galarneau <jeremie.galarneau@efficios.com>
src/common/utils.hpp

index 0d9f59afe8a929b1d5af477e9f1c57093320d251..68bef24b0fdd530fdd6eeb1ba99c1e93ddd7536a 100644 (file)
 
 #include <common/compat/directory-handle.hpp>
 #include <common/exception.hpp>
+#include <common/string-utils/c-string-view.hpp>
 
 #include <lttng/lttng-error.h>
 
+#include <fstream>
 #include <getopt.h>
+#include <iostream>
 #include <stdbool.h>
 #include <stdint.h>
 #include <sys/types.h>
@@ -75,4 +78,31 @@ enum lttng_error_code utils_check_enough_available_memory(uint64_t num_bytes,
  */
 int utils_parse_unsigned_long_long(const char *str, unsigned long long *value);
 
+/*
+ * Write a value to the given path and filename.
+ *
+ * Returns 0 on success and -1 on failure.
+ */
+template <typename ValueType>
+int utils_create_value_file(const ValueType value, const lttng::c_string_view filepath)
+{
+       DBG_FMT("Creating value file: path=`{}`, value={}", filepath, value);
+       try {
+               std::ofstream file;
+
+               file.exceptions(std::ofstream::failbit | std::ofstream::badbit);
+               /* Open the file with truncation to create or overwrite the file. */
+               file.open(filepath.data(), std::ios::out | std::ios::trunc);
+               file << value << std::endl;
+       } catch (const std::exception& e) {
+               ERR_FMT("Failed to produce value file: path=`{}`, value={}, error=`{}`",
+                       filepath,
+                       value,
+                       e.what());
+               return -1;
+       }
+
+       return 0;
+}
+
 #endif /* _COMMON_UTILS_H */
This page took 0.028983 seconds and 4 git commands to generate.