diff --git a/include/tmp/file b/include/tmp/file index 1ebf0cb..ffc061e 100644 --- a/include/tmp/file +++ b/include/tmp/file @@ -58,10 +58,14 @@ public: /// @throws std::filesystem::filesystem_error if cannot create a file static file text(std::string_view prefix = ""); - /// Reads the contents of this file + /// Streams the contents of this file /// @returns A file stream with this file contents std::ifstream read() const; + /// Reads the entire contents of this file + /// @returns A string with this file contents + std::string slurp() const; + /// Writes the given content to this file discarding any previous content /// @param content A string to write to this file void write(std::string_view content) const; diff --git a/lib/file.cpp b/lib/file.cpp index 772e8d1..3743b3b 100644 --- a/lib/file.cpp +++ b/lib/file.cpp @@ -60,6 +60,11 @@ std::ifstream file::read() const { : std::ifstream(file); } +std::string file::slurp() const { + std::ifstream stream = read(); + return std::string(std::istreambuf_iterator(stream), {}); +} + void file::write(std::string_view content) const { stream(*this, binary, /*append=*/false) << content; } diff --git a/tests/file_test.cpp b/tests/file_test.cpp index 2a7b583..7bc225f 100644 --- a/tests/file_test.cpp +++ b/tests/file_test.cpp @@ -101,6 +101,15 @@ TEST(FileTest, Read) { ASSERT_EQ(content, "Hello, world!"); } +TEST(FileTest, Slurp) { + const auto tmpfile = tmp::file(PREFIX); + tmpfile.write("Hello"); + tmpfile.append(", world!"); + + auto content = tmpfile.slurp(); + ASSERT_EQ(content, "Hello, world!"); +} + TEST(FileTest, Write) { const auto tmpfile = tmp::file(PREFIX); tmpfile.write("Hello");