From c182b25f363bd80a8043d8616dec9dff8cf8736b Mon Sep 17 00:00:00 2001 From: Andrei Alexandrescu Date: Tue, 27 Jan 2015 16:21:22 -0800 Subject: [PATCH] Add writeFile function to folly Summary: Reciprocal of readFile Test Plan: fbmake runtests Reviewed By: tudorb@fb.com Subscribers: trunkagent, net-systems@, folly-diffs@ FB internal diff: D1807551 Signature: t1:1807551:1422410565:f5bda294deb788da9f3881c19bb20cfa1f588c09 --- folly/FileUtil.h | 26 ++++++++++++++++++++++++++ folly/test/FileUtilTest.cpp | 9 ++------- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/folly/FileUtil.h b/folly/FileUtil.h index 2679f928..71d8e255 100644 --- a/folly/FileUtil.h +++ b/folly/FileUtil.h @@ -166,6 +166,32 @@ bool readFile(const char* file_name, Container& out, return true; } +/** + * Writes container to file. The container is assumed to be + * contiguous, with element size equal to 1, and offering STL-like + * methods empty(), size(), and indexed access + * (e.g. std::vector, std::string, fbstring, StringPiece). + * + * "flags" dictates the open flags to use. Default is to create file + * if it doesn't exist and truncate it. + * + * Returns: true on success or false on failure. In the latter case + * errno will be set appropriately by the failing system primitive. + */ +template +bool writeFile(const Container& data, const char* filename, + int flags = O_WRONLY | O_CREAT | O_TRUNC) { + static_assert(sizeof(data[0]) == 1, + "writeFile works with element size equal to 1"); + int fd = open(filename, flags, 0666); + if (fd == -1) { + return false; + } + bool ok = data.empty() || + writeFull(fd, &data[0], data.size()) == data.size(); + return closeNoInt(fd) == 0 && ok; +} + } // namespaces #endif /* FOLLY_FILEUTIL_H_ */ diff --git a/folly/test/FileUtilTest.cpp b/folly/test/FileUtilTest.cpp index 3b5ca72f..a315bb0d 100644 --- a/folly/test/FileUtilTest.cpp +++ b/folly/test/FileUtilTest.cpp @@ -251,13 +251,8 @@ TEST(String, readFile) { unlink(emptyFile.c_str()); }; - auto f = fopen(emptyFile.c_str(), "wb"); - EXPECT_NE(nullptr, f); - EXPECT_EQ(0, fclose(f)); - f = fopen(afile.c_str(), "wb"); - EXPECT_NE(nullptr, f); - EXPECT_EQ(3, fwrite("bar", 1, 3, f)); - EXPECT_EQ(0, fclose(f)); + EXPECT_TRUE(writeFile(string(), emptyFile.c_str())); + EXPECT_TRUE(writeFile(StringPiece("bar"), afile.c_str())); { string contents; -- 2.34.1