From: Tom Jackson Date: Tue, 5 Mar 2013 19:05:28 +0000 (-0800) Subject: File::tryOpen X-Git-Tag: v0.22.0~1045 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=9d6c66ddc8f6f38eef4c6f1c09abb3b30f888057;p=folly.git File::tryOpen Summary: Now that we have truthy files, it would be nice to be able to simply //try// opening files and return a possibly-initialized File. Test Plan: Unit tests Reviewed By: chaoyc@fb.com FB internal diff: D726916 --- diff --git a/folly/File.cpp b/folly/File.cpp index 1262dd1c..4998ec1f 100644 --- a/folly/File.cpp +++ b/folly/File.cpp @@ -79,6 +79,16 @@ File::~File() { return File(fd, true); } +/* static */ File File::tryOpen(const char* name, + int flags, + mode_t mode) { + try { + return File(name, flags, mode); + } catch (const std::system_error&) { + return File(); + } +} + void File::release() { fd_ = -1; ownsFd_ = false; diff --git a/folly/File.h b/folly/File.h index e990c91b..edcad920 100644 --- a/folly/File.h +++ b/folly/File.h @@ -54,6 +54,14 @@ class File { */ static File temporary(); + /** + * Attempts to open the file at the given path. Returns an 'closed` File + * instance on failure, which will evaluate to false. + */ + static File tryOpen(const char* name, + int flags = O_RDONLY, + mode_t mode = 0644); + /** * Return the file descriptor, or -1 if the file was closed. */ diff --git a/folly/test/FileTest.cpp b/folly/test/FileTest.cpp index 4f47f0fe..96ebb7e5 100644 --- a/folly/test/FileTest.cpp +++ b/folly/test/FileTest.cpp @@ -122,3 +122,8 @@ TEST(File, Truthy) { EXPECT_TRUE(false); } } + +TEST(File, TryOpen) { + EXPECT_FALSE(!!File::tryOpen("does_not_exist.txt")); + EXPECT_TRUE(!!File::tryOpen("/etc/fstab")); +}