From: Kienan Stewart Date: Mon, 25 Nov 2024 16:06:39 +0000 (-0500) Subject: utils: Add generic helper to create value files X-Git-Url: https://git.lttng.org./?a=commitdiff_plain;h=0c6dcc0887179d4ae7b0a57c602fc73b0eedaeba;p=lttng-tools.git utils: Add generic helper to create value files Change-Id: Ie814a4ddd22d9af578a194b73ed52b65df5128e4 Signed-off-by: Kienan Stewart Signed-off-by: Jérémie Galarneau --- diff --git a/src/common/utils.hpp b/src/common/utils.hpp index 0d9f59afe..68bef24b0 100644 --- a/src/common/utils.hpp +++ b/src/common/utils.hpp @@ -10,10 +10,13 @@ #include #include +#include #include +#include #include +#include #include #include #include @@ -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 +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 */