Skip to content

Commit

Permalink
Add test reopening an ofstream after close()
Browse files Browse the repository at this point in the history
Based on code reported at boostorg#150
  • Loading branch information
Flamefire committed Mar 17, 2022
1 parent 9b7dbd2 commit df7b4b6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions include/boost/nowide/filebuf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ namespace nowide {
{
if(std::fwrite(pbase(), 1, n, file_) != n)
return EOF;
assert(buffer_);
setp(buffer_, buffer_ + buffer_size_);
if(c != EOF)
{
Expand Down
33 changes: 33 additions & 0 deletions test/test_ofstream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,38 @@ void test_move_and_swap(const std::string& filename)
TEST_EQ(read_file(filename2), "Foo Bar");
}

// Based on bug reported in #150
void test_reopen(const std::string& filename)
{
const std::string filename2 = filename + ".2";
const std::string filename3 = filename + ".3";
remove_file_at_exit _(filename);
remove_file_at_exit _2(filename2);
remove_file_at_exit _3(filename3);

nw::ofstream f(filename, std::ios_base::binary);
using nw::test::data_type;
// Data sizes were randomly selected but above the usual default buffer size of 512
const std::string testData = nw::test::create_random_data(613, data_type::binary);
TEST(f.write(testData.c_str(), testData.size()));
f.close();
TEST_EQ(read_file(filename, data_type::binary), testData);

// Reopen via open-function
f.open(filename2, std::ios_base::binary);
const std::string testData2 = nw::test::create_random_data(523, data_type::binary);
TEST(f.write(testData2.c_str(), testData2.size()));
f.close();
TEST_EQ(read_file(filename2, data_type::binary), testData2);

// Reopen via move-assign
f = nw::ofstream(filename3, std::ios_base::binary);
const std::string testData3 = nw::test::create_random_data(795, data_type::binary);
TEST(f.write(testData3.c_str(), testData3.size()));
f.close();
TEST_EQ(read_file(filename3, data_type::binary), testData3);
}

// coverity [root_function]
void test_main(int, char** argv, char**)
{
Expand All @@ -180,4 +212,5 @@ void test_main(int, char** argv, char**)
test_open(exampleFilename.c_str());
test_open(exampleFilename);
test_move_and_swap(exampleFilename);
test_reopen(exampleFilename);
}

0 comments on commit df7b4b6

Please sign in to comment.