Skip to content

Commit

Permalink
Add tmp::file::read method (#18)
Browse files Browse the repository at this point in the history
Implement tmp::file::read method, which returns the ifstream for the file
  • Loading branch information
bugdea1er authored Feb 28, 2024
1 parent 6e583fa commit 270834a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
5 changes: 5 additions & 0 deletions include/tmp/file
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <tmp/path>

#include <filesystem>
#include <fstream>
#include <string_view>

namespace tmp {
Expand Down Expand Up @@ -57,6 +58,10 @@ public:
/// @throws std::filesystem::filesystem_error if cannot create a file
static file text(std::string_view prefix = "");

/// Reads the contents of this file
/// @returns A file stream with this file contents
std::ifstream read() 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
7 changes: 7 additions & 0 deletions lib/file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ file file::text(std::string_view prefix) {
return file(prefix, /*binary=*/false);
}

std::ifstream file::read() const {
const fs::path& file = *this;
return binary
? std::ifstream(file, std::ios::binary)
: std::ifstream(file);
}

void file::write(std::string_view content) const {
stream(*this, binary, /*append=*/false) << content;
}
Expand Down
11 changes: 11 additions & 0 deletions tests/file_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,17 @@ TEST(FileTest, MoveAssignment) {
ASSERT_EQ(fs::path(fst), path2);
}

TEST(FileTest, Read) {
const auto tmpfile = tmp::file(PREFIX);
tmpfile.write("Hello");
tmpfile.append(", world!");

auto stream = tmpfile.read();

auto content = std::string(std::istreambuf_iterator<char>(stream), {});
ASSERT_EQ(content, "Hello, world!");
}

TEST(FileTest, Write) {
const auto tmpfile = tmp::file(PREFIX);
tmpfile.write("Hello");
Expand Down

0 comments on commit 270834a

Please sign in to comment.