diff --git a/io/misc.cpp b/io/misc.cpp index 9c6a90c..ed6290e 100644 --- a/io/misc.cpp +++ b/io/misc.cpp @@ -11,6 +11,7 @@ namespace CppUtilities { * \brief Reads all contents of the specified file in a single call. * \throws Throws std::ios_base::failure when an error occurs or the specified \a maxSize * would be exceeded. + * \todo Use std::string_view to pass \a path in v6. */ std::string readFile(const std::string &path, std::string::size_type maxSize) { @@ -28,4 +29,20 @@ std::string readFile(const std::string &path, std::string::size_type maxSize) res.assign((istreambuf_iterator(file)), istreambuf_iterator()); return res; } + +/*! + * \brief Writes all \a contents to the specified file in a single call. + * \throws Throws std::ios_base::failure when an error occurs. + * \remarks Closing the file manually to prevent flushing the file within the d'tor which + * would suppress an exception + */ +void writeFile(std::string_view path, std::string_view contents) +{ + NativeFileStream file; + file.exceptions(ios_base::failbit | ios_base::badbit); + file.open(path.data(), ios_base::out | ios_base::trunc | ios_base::binary); + file.write(contents.data(), static_cast(contents.size())); + file.close(); +} + } // namespace CppUtilities diff --git a/io/misc.h b/io/misc.h index 47809fc..86739ba 100644 --- a/io/misc.h +++ b/io/misc.h @@ -4,10 +4,12 @@ #include "../global.h" #include +#include namespace CppUtilities { CPP_UTILITIES_EXPORT std::string readFile(const std::string &path, std::string::size_type maxSize = std::string::npos); -} +CPP_UTILITIES_EXPORT void writeFile(std::string_view path, std::string_view contents); +} // namespace CppUtilities #endif // IOUTILITIES_MISC_H diff --git a/tests/iotests.cpp b/tests/iotests.cpp index 79974c6..0e596d3 100644 --- a/tests/iotests.cpp +++ b/tests/iotests.cpp @@ -47,6 +47,7 @@ class IoTests : public TestFixture { CPPUNIT_TEST(testIniFile); CPPUNIT_TEST(testCopy); CPPUNIT_TEST(testReadFile); + CPPUNIT_TEST(testWriteFile); CPPUNIT_TEST(testAnsiEscapeCodes); #ifdef CPP_UTILITIES_USE_NATIVE_FILE_BUFFER CPPUNIT_TEST(testNativeFileStream); @@ -64,6 +65,7 @@ public: void testIniFile(); void testCopy(); void testReadFile(); + void testWriteFile(); void testAnsiEscapeCodes(); #ifdef CPP_UTILITIES_USE_NATIVE_FILE_BUFFER void testNativeFileStream(); @@ -366,6 +368,19 @@ void IoTests::testReadFile() #endif } +/*! + * \brief Tests writeFile(). + */ +void IoTests::testWriteFile() +{ + const string path(workingCopyPath("test.ini", WorkingCopyMode::NoCopy)); + writeFile(path, "some contents"); + CPPUNIT_ASSERT_EQUAL("some contents"s, readFile(path)); +} + +/*! + * \brief Tests formatting functions of CppUtilities::EscapeCodes namespace. + */ void IoTests::testAnsiEscapeCodes() { stringstream ss1;