1

I'm trying to accomplish binary i/o here and I keep getting this error which is...

no matching function for call to 'std::basic_ofstream<char>::write(int*,unsigned int)'

and

no matching function for call to 'std::basic_ofstream<char>::write(double*,unsigned int)'

Here is my code...

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

using namespace std;

int main()
{
    int x = 123;
    double fx = 12.34;
    ofstream myfile("filename.dat", ios::out | ios::binary);
    myfile.write(&x, sizeof(x));
    myfile.write(&fx, sizeof(fx));
    myfile.close();
    return 0;
}

I've found multiple other posts with the same situation but their fix was usually typing in...

ofstream myfile(filename.c_str(), ios::out | ios::binary);

The compiler still screams at me as I tried it multiple times. I'm using QT creator as my IDE which I've already verified it is using C++11. and also ran the same code in Code::Blocks and get the same error. Its not liking the filename parameter i'm passing to it. I think this has something to do with the first parameter being the const char of the member function of ofstream open()?!

void open(const char *filename, [int mode], [int prot]);

What am I not understanding/missing here?

Shane Yost
  • 231
  • 6
  • 14
  • 1
    What you're missing is that there are no `write` overloads for every type you can think of. If you want to do binary I/O, you should be explicit about it by casting the pointer to memory that holds the object to `const char *`. – Kuba hasn't forgotten Monica Jul 20 '16 at 18:39

1 Answers1

1

write() is a function for outputting characters, it won't apply any formatting, you need to do the formatting yourself.

The function requires a const char* argument. It won't take pointers to other types, a conversion will need to be made first.

See here for more details.

The stream operator << is better suited if you want the stream to format your output.

Niall
  • 30,036
  • 10
  • 99
  • 142