我可以将这两种方法/函数合二为一吗?

Can I combine these 2 methods/functions into one?

本文关键字:函数 合二为一 方法 两种 我可以      更新时间:2023-10-16

我写了下面的代码。其中一个方法将检查是否可以访问信号文件,另一个将检查后台文件是否可以存在。

bool signalFileExist(string signalFile){
    ifstream f(signalFile.c_str());
    if(f.good()){
        f.close();
        return true;
    }
    f.close();
    return false;
}
bool backgroundFileExist (string backgroundFile){
    ifstream f(backgroundFile.c_str());
    if(f.good()){
        f.close();
        return true;
    }
    f.close();
    return false;
}

我的问题是:我可以将这两种方法合二为一吗? 此外,如果无法检查,我需要告诉用户哪个文件是坏的。是否可以以执行此操作的方式编写方法?

他们...方法完全相同吗?

您可以删除其中任何一个,然后将另一个重命名为类似以下内容:

bool fileExists(string fileName){
    ifstream f(fileName.c_str());
    if(f.good()){
        f.close();
        return true;
    }
    f.close();
    return false;
}

如果你想告诉用户哪个文件是坏的,如果你有文件名,你可以在函数中做,或者你可以在调用站点做。