Add writeFile function to folly
authorAndrei Alexandrescu <aalexandre@fb.com>
Wed, 28 Jan 2015 00:21:22 +0000 (16:21 -0800)
committerwoo <woo@fb.com>
Mon, 2 Feb 2015 21:12:57 +0000 (13:12 -0800)
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
folly/test/FileUtilTest.cpp

index 2679f928f1add40886c1e3dfb0b1fe1a23134d08..71d8e2551274089e9cf1cec503557790ccaf3168 100644 (file)
@@ -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<char>, 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 <class Container>
+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_ */
index 3b5ca72f1f8bef79ead69685618d99c45549325f..a315bb0dba968d142f25a215e5b4450c497b1a49 100644 (file)
@@ -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;