如何避免这种嵌套的 if 语句?

How to avoid this nested if statement?

我想检查一个文件是否存在于两个不同的路径中。如果第一个没有,请检查第二个。

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;

如何避免嵌套的 if 语句?最好,为了便于阅读,我不想嵌套 if 语句。 这里的问题是,如果第一个确实有效,我不希望它检查第二个 if 语句。

我考虑过使用:

如果您不关心打开的是哪个文件,您可以这样做

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;
}
...

否则如果你真的只想要一个if你可以

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;
}
...

但这使得代码不如两个 ifs

清晰

P.S。不要考虑使用 goto

我想这个模式很普遍:你可以尝试任意多的路径:

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;