Commit 9d6c66dd authored by Tom Jackson's avatar Tom Jackson Committed by Jordan DeLong

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
parent 9d7cc509
......@@ -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;
......
......@@ -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.
*/
......
......@@ -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"));
}
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