C++无法在函数内检查 ifstream/ofstream.is_open()



我用C++编写了一个代码,它从文本文件中读取或使用ifstream/ofstream创建新文件。我想添加一个检查.is_open fstream的成员函数,以查看文件是否已成功打开。它在主循环中正常工作。然后我尝试为此目的在循环外创建一个函数,并在 main 内调用它,我得到以下错误:

std::ios_base::ios_base(const std::ios_base&)是私密的。

是否可以在主循环之外进行检查?如何?我做错了什么?

如果您能提供帮助,我将不胜感激。您可以在下面找到代码。

附言我是C++的新手,所以如果你看到任何不专业的编程方法,请不要过度批评。尽管任何改进建议都非常受欢迎。

#include <iostream>
#include <fstream>
using namespace std;
void check_opened(ifstream toget, ofstream togive){
    if(toget.is_open()){
        cout<<"able to open file(toread.txt)"<<endl;
    }
    else {
        cout<<"failure"<<endl;
    }
    if(togive.is_open()){
        cout<<"able to create/open a file(newone.txt)"<<endl;
    }
    else {
        cout<<"failure"<<endl;
    }
}
int main () {
    ifstream toget;
    ofstream togive;
    toget.open("toread.txt");
    togive.open("newone.txt");
    check_opened(toget,togive);
    toget.close();
    togive.close();
  return 0;
}

函数 check_opened 不引用流,而是引用流。 因此,当您调用 main 函数时check_opened隐式调用 ifstreamofstream 的复制构造函数,它们是私有的,这会导致错误。 将check_opened的签名更改为void check_opened(ifstream&, ofstream&)将解决您的问题。

相关内容

最新更新