Search code examples
c++scopefstreamifstreamofstream

C++ unable check ifstream/ofstream.is_open() inside a function


I have written a code in C++ which reads from a text file or creates new one with with ifstream/ofstream. I wanted to add a check with .is_open member function of fstream to see if the files were successfully opened. It works correctly inside main loop. Then I tried to create a function outside the loop for this purpose, and call it inside main, and I got following error:

std::ios_base::ios_base(const std::ios_base&) is private.

Is it possible to make the check outside of main loop? How? What am I doing wrong?

I would appreciate if you can help. You can find the code below.

P.S. I am newbie in C++, so please don't overcriticize unprofessional programming approaches if you see any. Though any recommendations for improvement are more than welcome.

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

Solution

  • The function check_opened does not take a reference to a stream, it takes a copy of one. Thus when you call check_opened your main function implicitly invokes the copy constructor of ifstream and ofstream, which are private, which causes the error. Changing the signature of check_opened to void check_opened(ifstream&, ofstream&) will solve your problem.