brohjoe
brohjoe

Reputation: 932

Reference to an fstream object creating an error

I'm getting an error running a program that demonstrates how file stream objects may be passed by reference to functions. The program fails when making a call to the file.open(name, ios::in) function:

  #include<iostream>
    #include<fstream>
    #include<string>

    using namespace std;

    //function prototypes
    bool openFileIn(fstream &, string);
    void showContents(fstream &);

    int main(){
        fstream dataFile;

    if (openFileIn(dataFile, "demofile.txt"))
    {
        cout << "File opened successfully.\n";
        cout << "Now reding data from the file. \n\n";
        showContents(dataFile);
        dataFile.close();
        cout << "\nDone. \n";
    }
    else
        cout <<"File open error! "<< endl;

    return 0;
}

//******************************************************************
//Definition of function openFileIn. Accepts a reference to an     
//fstream object as an argument.  The file is opened for input. 
//The function returns true upon success, false upon failure.   
//******************************************************************

bool openFileIn(fstream& file, string name)
{
    file.open(name, ios::in);  //error occurs here

    if (file.fail())
        return false;

    else
        return true;

}

//*******************************************************************
//Defintion of function showContents. Accepts an fstream reference
//as its argument. Uses a loop to read each name from the file and
//displays it on the screen.
//*******************************************************************

void showContents(fstream &file)
{
    string line;

    while(file >> line)
    {
        cout << line << endl;
    }

}

The error occurs in the 'openFileIn()' function. The 'file.open()' call fails with an error. Here is the stacktrace:

Stacktrace

Upvotes: 0

Views: 115

Answers (1)

Heisenbug
Heisenbug

Reputation: 39204

The open function overload taking std::string as parameter, is defined starting from C++11.

You are likely to be using an old compiler, so you need to use the old open signature using const char *.

Try:

file.open(name.c_str(), ios::in);

I'm getting an error running a program that demonstrates how file stream objects may be passed by reference to functions. The program fails when making a call to the file.open(name, ios::in) function

Note that your program is not compiling at all. What you see in the output is a compiling error, not a stacktrace.

Upvotes: 2

Related Questions