c++ - 程序应何时通知用户它无法打开文件?

标签 c++ c++11 ifstream file-read

我有一个程序可以创建一个对象并使用该对象的一个​​函数,该函数接受两个文件名并从中读取数据并设置其值。

对象应该检查 ifstream 是自己打开还是应该在 main 函数中完成,首先尝试创建一对 ifstream 值并将它们传递给这个函数?有一个草图:

int main() {

    Myclass *m = new Myclass();

    string file1, file2;
    …initialize file1, file2…

    Myclass.readFromFiles(file1, file2);

    delete m;
}

在我的课上:

void readFromFiles(const string &file1, const string &file2) {
    std::ifstream infile1(file1);
    if (!infile1.is_open()) {  throw std::runtime_error("Could not open file"); }
    infile1 >> value;

    std::ifstream infile2(file2);
    if (!infile2.is_open()) {  throw std::runtime_error("Could not open file"); }
    infile2 >> value2 >> value3;
}

或者说

std::ifstream open_file(std::string filename) {
    std::ifstream infile(posesFilename);
    if (!infile.is_open()) {
        throw std::runtime_error("Could not open file");
    }
    else
        return infile;
}

int main() {

    Myclass *m = new Myclass();

    string file1, file2;
    …initialize file1, file2…
    try{
        std::ifstream f1 = open_file(file1);
        std::ifstream f2 = open_file(file2);

        Myclass.readFromFiles(f1, f2);
    }catch (runtime_error e){
       cout<< e.what() <<endl;
    }

    delete m;
}

在我的课上:

void readFromFiles(std::ifstream &f1, std::ifstream &f2)
    f1 >> value;
    f2 >> value2 >> value3;
}

最佳答案

在前一种情况下,您正在让函数调用者的生活更轻松。他们只需要将两个文件名传递给您的方法。该方法负责打开和关闭文件。如果您从多个位置调用此方法,您就减少了重复代码的数量。它也不是很灵活:如果调用者有 ifstream& 引用,但没有文件名,他们不能调用你的 readFromFiles(filename1, filename2) 方法。

在后一种情况下,调用者可以调用您的 readFromFiles(),无论他们是否有 ifstream& 引用,或者如果他们只有文件名,则首先打开文件。此外,可以使该方法更加灵活。将预期参数更改为 istream& 而不是 ifstream& 将允许您使用任何输入流作为源来读取数据。例如,可以在构造 std:strstream 的地方创建一个单元测试,并将其传递给您的读取数据方法。

为了两全其美,提供两种方法:

void readFromFiles(const string &file1, const string &file2) {
    std:ifstream f1(file1);
    if (!f1.is_open()) {  throw std::runtime_error("Could not open file"); }
    std:ifstream f2(file2);
    if (!f2.is_open()) {  throw std::runtime_error("Could not open file"); }
    readFromFiles(f1, f2);
}

void readFromFiles(std:istream& f1, std:istream& f2) {
   // ...
}

您为调用者提供了便利和灵 active 。如果调用者需要知道这两个文件中的哪一个未能打开(例如,如果“file1”不存在,他们可能想回退到“file1_default”,如果“file2”不存在,则回退到“file2_default” ),他们可以完全控制打开文件和任何打开失败的报告。

关于c++ - 程序应何时通知用户它无法打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35997988/

相关文章:

c++ - 关于转换运算符和operator()

c++ - 正确使用 ifstream 对象作为类的成员

c++ - 如何将 C++ 代码集成到工作的 LAPACK 代码中

C++ Variadic Vector 运算符实现

c++ - 计算二叉树中具有特定数量子节点的节点?

C++ 求值顺序

c++ - 逐行读取txt

c++ - 非特化模板中模板特化的成员访问

c++ - 如何在c++中使用每个循环

c++ - 我可以有一个异常的静态全局实例吗?