error in C++, what to do ?: could not find an match for ostream::write(long *, unsigned int)
-
21-09-2019 - |
Question
I am trying to write data stored in a binary file using turbo C++. But it shows me an error
could not find an match for ostream::write(long *, unsigned int)
I want to write a 4 byte long
data into that file. When i tries to write data using char pointer. It runs successfully. But i want to store large value i.e. eg. 2454545454
Which can be stored in long
only.
I dont know how to convert 1 byte into bit. I have 1 byte of data as a character. Moreover what i m trying to do is to convert 4 chars into long and store data into it. And at the other side i want to reverse this so as to retrieve how many bytes of data i have written.
long *lmem;
lmem=new long;
*lmem=Tsize;
fo.write(lmem,sizeof(long));// error occurs here
delete lmem;
I am implementing steganography and i have successfully stored txt file into image but trying to retrieve that file data now.
EDIT:
I am using Turbo Complier.
Solution
Cast it to a char*
long *lmem;
lmem=new long;
*lmem=Tsize;
fo.write(reinterpret_cast<char*>(lmem),sizeof(long));
delete lmem;
Or even better (as allocation on the stack is far faster and less error prone)
long lmem = Tsize;
fo.write(reinterpret_cast<char*>(&lmem),sizeof(long));
If Tsize
is addressable and a long you could do this:
fo.write(reinterpret_cast<char*>(&Tsize),sizeof(long));
OTHER TIPS
I believe write takes a char* , not a long*
ostream& write ( const char* s , streamsize n );
1)
const long L = Tsize;
fo.write(reinterpret_cast<const char*>(&L),sizeof(L));
There are several problems here.
First, you don't need to create an all new long
to store Tsize in. You can make a pointer to the Tsize you already have.
Second, the write
call takes a stream of bytes. What you need to do is to cast your pointer to char*.
Like this:
fo.write( static_cast<char*>(&Tsize), sizeof(Tsize) );
Third, writing one long like this is pretty inefficient. If you have a large array of long values that you want to write, use a single write call to get all of them, like:
fo.write( static_cast<char*>(array), sizeof(*array) * array_count );
I am pretty sure static_cast works for pointers here, but if it does not then change the code to use reinterpret_cast
.