From: Joel Rosdahl Date: Mon, 18 May 2020 18:03:24 +0000 (+0200) Subject: Use std::ios_base::openmode as the third Util::write_file parameter X-Git-Tag: v4.0~440 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e2effaa431d9644bfb6ec38b293c70b8ceaa2305;p=thirdparty%2Fccache.git Use std::ios_base::openmode as the third Util::write_file parameter --- diff --git a/src/Util.cpp b/src/Util.cpp index 104abb007..d951be2d0 100644 --- a/src/Util.cpp +++ b/src/Util.cpp @@ -762,10 +762,12 @@ wipe_path(const std::string& path) } void -write_file(const std::string& path, const std::string& data, bool binary) +write_file(const std::string& path, + const std::string& data, + std::ios_base::openmode open_mode) { - std::ofstream file(path, - binary ? std::ios::out | std::ios::binary : std::ios::out); + open_mode |= std::ios::out; + std::ofstream file(path, open_mode); if (!file) { throw Error(strerror(errno)); } diff --git a/src/Util.hpp b/src/Util.hpp index 44c2306b9..38c49861e 100644 --- a/src/Util.hpp +++ b/src/Util.hpp @@ -311,12 +311,14 @@ bool unlink_tmp(const std::string& path, // Throws Error on error. void wipe_path(const std::string& path); -// Write file data from a string. +// Write file data from a string. The file will be opened according to +// `open_mode`, which always will include `std::ios::out` even if not specified +// at the call site. // // Throws `Error` on error. The description contains the error message without // the path. void write_file(const std::string& path, const std::string& data, - bool binary = false); + std::ios_base::openmode open_mode = std::ios::out); } // namespace Util diff --git a/unittest/test_Util.cpp b/unittest/test_Util.cpp index ade6875bc..d68f009fe 100644 --- a/unittest/test_Util.cpp +++ b/unittest/test_Util.cpp @@ -482,6 +482,14 @@ TEST_CASE("Util::read_file and Util::write_file") std::string data = Util::read_file("test"); CHECK(data == "foo\nbar\n"); + Util::write_file("test", "car"); + data = Util::read_file("test"); + CHECK(data == "car"); + + Util::write_file("test", "pet", std::ios::app); + data = Util::read_file("test"); + CHECK(data == "carpet"); + CHECK_THROWS_WITH(Util::read_file("does/not/exist"), Equals("No such file or directory"));