Skip to content

Commit

Permalink
Avoid adding duplicate strings in a file: addStringToFile() (#22)
Browse files Browse the repository at this point in the history
* Check if string contains lines before adding new (duplicated) ones

Signed-off-by: lbgracioso <[email protected]>

* Quick change on the LOG message

Signed-off-by: Vinícius Ferrão <[email protected]>

---------

Signed-off-by: lbgracioso <[email protected]>
Signed-off-by: Vinícius Ferrão <[email protected]>
Co-authored-by: Vinícius Ferrão <[email protected]>
  • Loading branch information
lbgracioso and viniciusferrao committed Aug 23, 2023
1 parent 0f42deb commit 947ff2a
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include <fmt/format.h>

#include <cloysterhpc/services/log.h>
#include <fstream>

namespace cloyster {

Expand Down Expand Up @@ -191,6 +192,16 @@ void changeValueInConfigurationFile(

void addStringToFile(std::string_view filename, std::string_view string)
{
// Check if file already contains the string to avoid duplicate lines.
std::ifstream ifs(std::string { filename });
std::string content((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));

if (content.find(string) != std::string::npos) {
LOG_DEBUG("File {} already contains line(s):\n{}\n", filename, string);
return;
}

#ifdef _LIBCPP_VERSION
std::ofstream file(filename, std::ios_base::app);
#else
Expand Down

0 comments on commit 947ff2a

Please sign in to comment.