Commit c182b25f authored by Andrei Alexandrescu's avatar Andrei Alexandrescu Committed by woo

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
parent 5a8d191e
...@@ -166,6 +166,32 @@ bool readFile(const char* file_name, Container& out, ...@@ -166,6 +166,32 @@ bool readFile(const char* file_name, Container& out,
return true; 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 } // namespaces
#endif /* FOLLY_FILEUTIL_H_ */ #endif /* FOLLY_FILEUTIL_H_ */
...@@ -251,13 +251,8 @@ TEST(String, readFile) { ...@@ -251,13 +251,8 @@ TEST(String, readFile) {
unlink(emptyFile.c_str()); unlink(emptyFile.c_str());
}; };
auto f = fopen(emptyFile.c_str(), "wb"); EXPECT_TRUE(writeFile(string(), emptyFile.c_str()));
EXPECT_NE(nullptr, f); EXPECT_TRUE(writeFile(StringPiece("bar"), afile.c_str()));
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));
{ {
string contents; string contents;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment