Search code examples
c++eclipsefstream

Why doesnt my fstream access compile?


I have a problem. I'm making a program in C++ and I want to have access to some files, so I use the class fstream. Well, here it's all ok, but when I'm going to compile the program it crashes and gives me an error.

I put here the code in which I connect the file:

#include <iostream>
#include <fstream>
#include <map>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <string.h>

using namespace std;

fstream file1, file2;

void access();

int main(){
   access();

   file1.close();
   file2.close();
}

void access(){

    file1("C:\\data\\file1.dat",ios::in | ios::out | ios::binary);
    cout << "Opening File1..." << endl;

    file2("C:\\data\\file2.dat",ios::in | ios::out | ios::binary);
    cout << "Opening File2..." << endl;

}

And it gives me the following error:

no match for call to '(std::fstream {aka std::basic_fstream<char>}) (const char [20], std::_Ios_Openmode)'

So I tried to put the method access like this:

void access(){
        string f1 = "C:\\data\\file1.dat";
        string f2 = "C:\\data\\file2.dat";


        file1(f1.c_str(),ios::in | ios::out | ios::binary);
        cout << "Opening File1..." << endl;

        file2(f2.c_str(),ios::in | ios::out | ios::binary);
        cout << "Opening File2..." << endl;

    }

But it gives me also an error. Its the following:

no match for call to '(std::fstream {aka std::basic_fstream<char>}) (const char*, std::_Ios_Openmode)'

I don't have any idea about what happens, any help would be appreciated.

Thank you very much.


Solution

  • Even though it might look like it, this is not a call to the constructor, as it has already been declared and constructed in global space.

    file1("C:\\data\\file1.dat",ios::in | ios::out | ios::binary);

    This is a call to operator(). Try to use open instead:

    file1.open("C:\\data\\file1.dat",ios::in | ios::out | ios::binary);