Skip to content

Commit

Permalink
Add tmp::file::write and tmp::file::append
Browse files Browse the repository at this point in the history
  • Loading branch information
bugdea1er committed Jan 25, 2024
1 parent c42db67 commit 4bf4412
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
14 changes: 12 additions & 2 deletions include/tmp/file.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ namespace tmp {
/// <system's default location for temporary files>/prefix/. The prefix can be
/// a path consisting of multiple segments.
///
/// The tmp::file class also provides an additional operator<< which allows
/// writing data to the temporary file using the same syntax as std::cout.
/// The tmp::file class also provides an additional write and append methods
/// which allow writing data to the temporary file.
///
/// When the object is destroyed, it deletes the temporary file.
///
Expand Down Expand Up @@ -94,6 +94,16 @@ class file {
return std::addressof(this->p);
}

/// Writes the given @p content to this file discarding any previous content
void write(std::string_view content, std::ios_base::openmode mode = 0) {
std::ofstream { this->path(), std::ios_base::trunc | mode } << content;
}

/// Appends the given @p content to the end of this file
void append(std::string_view content, std::ios_base::openmode mode = 0) {
std::ofstream { this->path(), std::ios_base::app | mode } << content;
}

/// Deletes this file when the enclosing scope is exited
~file() noexcept { this->remove(); }

Expand Down
23 changes: 18 additions & 5 deletions tests/file_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,24 @@ TEST(FileTest, MoveAssignment) {
ASSERT_TRUE(fs::exists(fst));
}

TEST(FileTest, Streaming) {
TEST(FileTest, Write) {
const auto tmpfile = file();
tmpfile << "Hi";
tmpfile.write("Hello");

std::string s;
std::fstream(tmpfile.path(), std::ios::in) >> s;
ASSERT_EQ(s, "Hi");
std::ifstream stream(tmpfile.path());
std::string content(std::istreambuf_iterator<char>(stream), {});
ASSERT_EQ(content, "Hello");
}

TEST(FileTest, Append) {
const auto tmpfile = file();
tmpfile.write("Hello");

tmpfile.append(", world!");

std::cout << tmpfile.path() << std::endl;

std::ifstream stream(tmpfile.path());
std::string content(std::istreambuf_iterator<char>(stream), {});
ASSERT_EQ(content, "Hello, world!");
}

0 comments on commit 4bf4412

Please sign in to comment.