Reputation: 23
I want to check if one file exists in two different paths. If the first one doesn't, check the second.
filepath1 = "/path1/file.txt"
filepath2 = "/path2/file.txt"
file_descriptor = open(filepath1)
if ( !file_descriptor.open() )
{
print("file 1 did not work");
//try file 2
file_descriptor = open(filepath2);
if( !file_descriptor.open() )
{
print("could not open file 2. exiting.");
return false;
}
}
//we get here and file_descriptor should point to a valid file
read_file(file_descriptor);
return true;
How can I avoid the nested if
statement? Preferably, I'd like to not nest the if
statements for readability.
The problem here is that if the first one does work, I don't want it to check the second if
statement.
I thought about using:
goto
(I want to avoid this)Upvotes: 2
Views: 122
Reputation: 2861
I guess this pattern is pretty general: you can try as many paths as you wish:
auto filepath1 = "/path1/file.txt";
auto filepath2 = "/path2/file.txt";
// We assume file_descriptor has been declared earlier
for (const auto fpath: {filepath1, filepath2})
{
file_descriptor = open(fpath)
if (file_descriptor.open())
break;
else
printf("file %s did not work\n", fpath);
}
if (!file_descriptor.open()) return false; // or throw
read_file(file_descriptor);
return true;
Upvotes: 1
Reputation: 32586
if you don't care about which file is open you can do
filepath1 = "/path1/file.txt"
filepath2 = "/path2/file.txt"
if (!(file_descriptor = open(filepath1)).open() &&
!(file_descriptor = open(filepath2)).open())
{
print("could not open file 1 nor 2. exiting.");
return false;
}
...
else if you really want only one if
you can do
filepath1 = "/path1/file.txt"
filepath2 = "/path2/file.txt"
if (!(file_descriptor = open(filepath1)).open() &&
(print("file 1 did not work"),
!(file_descriptor = open(filepath2)).open()))
{
print("could not open file 2. exiting.");
return false;
}
...
but this makes the code less clear than with the two if
s
P.S. do not think about using goto
Upvotes: 1