Compilation results in an error when trying to compile code containing binary ifstream

64 views Asked by At

I am running into a problem with the accessing a binary file via the input file stream class (ifstream).

My approach starts with the following calling function:

void ReadFile(vector<string>& argv, ostream& oss){
   string FileName = argv.at(2) + "INPUT" ;
   ifstream BinFile ;
   OpenBinaryFile(FileName, BinFile) ;
   return ;
}

The called function looks like this:

void OpenBinaryFile(string& FileName, ifstream& BinFile){
   using namespace std ;
   BinFile(FileName.c_str(),ifstream::binary | ifstream::in) ;
}

When I try to compile this simple scheme using gcc version 4.9.2 I get the following error:

error: no match for call to ‘(std::ifstream {aka std::basic_ifstream<char>}) (const char*, std::_Ios_Openmode)’
BinFile(FileName.c_str(),ifstream::binary | ifstream::in) ;
                                                        ^

I've tried to get the caret ("^") placed exactly where the compiler did.

What's going on here? I am baffled.

Thanks!

2

There are 2 answers

2
Lightness Races in Orbit On BEST ANSWER

There are two ways of opening a stream.

  1. During construction, in a declaration:

    std::ifstream BinFile(filename, std::ifstream::binary | std::ifstream::in);
    
  2. After construction, using the std::ifstream::open function:

    std::ifstream BinFile;
    BinFile.open(filename, std::ifstream::binary | std::ifstream::in);
    

In your question you are attempting to mix the two. This results in an attempt to call the non-existent "function call operator" operator() on the object BinFile.

5
donjuedo On

As written, you were calling a constructor with the object that had already been constructed on the stack of the calling routine. See the constructor documented at http://www.cplusplus.com/reference/fstream/ifstream/ifstream/