From 119f7dc3d6dc02a07167a69a929cdfee9c0626e9 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Fri, 27 Nov 2020 08:15:14 -0800 Subject: [PATCH] Truncate file by default --- include/fmt/os.h | 5 +++-- test/os-test.cc | 13 +++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/include/fmt/os.h b/include/fmt/os.h index d945df47..f785c0a3 100644 --- a/include/fmt/os.h +++ b/include/fmt/os.h @@ -280,7 +280,8 @@ class file { WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only. RDWR = FMT_POSIX(O_RDWR), // Open for reading and writing. CREATE = FMT_POSIX(O_CREAT), // Create if the file doesn't exist. - APPEND = FMT_POSIX(O_APPEND) // Open in append mode. + APPEND = FMT_POSIX(O_APPEND), // Open in append mode. + TRUNC = FMT_POSIX(O_TRUNC) // Truncate the content of the file. }; // Constructs a file object which doesn't represent any file. @@ -357,7 +358,7 @@ struct buffer_size { }; struct ostream_params { - int oflag = file::WRONLY | file::CREATE; + int oflag = file::WRONLY | file::CREATE | file::TRUNC; size_t buffer_size = BUFSIZ > 32768 ? BUFSIZ : 32768; ostream_params() {} diff --git a/test/os-test.cc b/test/os-test.cc index 359b5ff8..ffe33d67 100644 --- a/test/os-test.cc +++ b/test/os-test.cc @@ -319,6 +319,19 @@ TEST(OStreamTest, BufferSize) { EXPECT_READ(in, "foo"); } +TEST(OStreamTest, Truncate) { + { + fmt::ostream out = fmt::output_file("test-file"); + out.print("0123456789"); + } + { + fmt::ostream out = fmt::output_file("test-file"); + out.print("foo"); + } + file in("test-file", file::RDONLY); + EXPECT_EQ("foo", read(in, 4)); +} + TEST(FileTest, DefaultCtor) { file f; EXPECT_EQ(-1, f.descriptor());