Skip to content

Commit

Permalink
Add tmp::file::slurp method (#19)
Browse files Browse the repository at this point in the history
Implement tmp::file::slurp method, which returns the entire contents for the file in a form of a string
  • Loading branch information
bugdea1er authored Mar 3, 2024
1 parent 270834a commit fcb102f
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
6 changes: 5 additions & 1 deletion include/tmp/file
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
5 changes: 5 additions & 0 deletions lib/file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<char>(stream), {});
}

void file::write(std::string_view content) const {
stream(*this, binary, /*append=*/false) << content;
}
Expand Down
9 changes: 9 additions & 0 deletions tests/file_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down

0 comments on commit fcb102f

Please sign in to comment.