Home > Back-end >  Pass ifstream object by reference to multiple functions
Pass ifstream object by reference to multiple functions

Time:06-22

I'd like to pass the same ifstream reference to multiple functions as shown below. But I noticed that the infile variable becomes null after the call f1( infile );

void f1(istream& infile)
{
    char c = file.get();
}

void f2(istream& infile)
{
    char c = file.get();
    // other read operations
}

int main()
{
    ifstream infile;
    infile.open("content.txt",std::ios_base::in);
    if ( infile.good() )
    {
        if (!infile)
        {
            cout << "file not open for f1\n";
        }
        f1( infile );
        if (!infile)
        {
            cout << "file not open for f2n";
        }
        f2( infile );
    }
    infile.close();
    return 0;
}

I'm wondering how to go about it if I don't want to create another ifstream variable? Thank you

CodePudding user response:

the infile variable becomes null

No, it doesn't. But it does become "failed". The ! operator on a stream is checking its failbit, not whether it is "null".

The reason it fails is that you are trying to output to an input-only stream. In fact, this code shouldn't even compile....

CodePudding user response:

As suggested by @BenVoigt, the second ! operator check was failing as the eof bit was set after the first read operation. The fix is below. (source)

infile.clear(); // clears fail and eof bits
infile.seekg(0, std::ios::beg); // move pointer back to start
  • Related