0

I want to encapsulate in/output into a function and call that function from main, but compiler shows me strange error once I did that

ifstream open_file(){
    ifstream in;
    string filename;
    cout << "Plean Enter File Name: ";
    cin >> filename;
    in.open(filename.c_str());
    while(true){
        if (in.fail()){
            cout << "Plean Enter File Name Again: ";
            cin >> filename;
            in.clear();
            in.open(filename.c_str());
        }
        else
            break;
    }
    return in;
}

call it from main

int main(){
    ifstream in;
    in = open_file();
    return 0;
}

error(7 errors)

Description Resource    Path    Location    Type
β€˜std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const   std::basic_streambuf<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]’ is private  Standford.Programming       line 802, external location: /usr/include/c++/4.8/streambuf C/C++ Problem
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Hello lad
  • 17,344
  • 46
  • 127
  • 200

2 Answers2

7

The compiler error is not strange, it's spot on since streams cannot be copied. The function open_file returns an ifstream object by value which is not supported.

ifstream open_file()
{
    ifstream in;

    // snip

    return in; // return the stream by value requires a copy.
}

One option is to pass a reference to a stream as an argument to the open_file function. This will allow the open_file function to handle opening the file and whatever function calls it the ability to read/write from/to the file. The following code should get you back on track...

bool open_file(ifstream& in)
{
    string filename;
    cout << "Plean Enter File Name: ";
    cin >> filename;
    in.open(filename.c_str());

    // [snipped code].
    return in.is_open();
}

int main()
{
    ifstream in;
    if(open_file(in))
    {
        // do something if the file is opened
    }
    return 0;
}
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
0

std::ifstream is not copyable but with C++11, it is moveable, so if you compile with c++11 enabled (-std=c++11 for gcc/clang), your code should compile.

Jarod42
  • 203,559
  • 14
  • 181
  • 302