Hi guys i have a problem while reading a binary file... I have written some data in binary format and want to read the data now... but when i print the data its coming a null ... ppls help me out
My code is as follows
cout<<sizeof(data);
will always return 4. sizeof() is compile time operator so will always return the wrong value.
file.read(reinterpret_cast<char *>(&ReadData),sizeof(BinaryIO));
this will always read 4 bytes as the size of class will be 4 always on 32bit.
do it simple. Also, if you want to read only characters from binary file it will work fine but for numbers, double or floats etc you need to join the bytes to form a full value and only then you can print it.
I think first you need to read the file correctly.
like: file.read(&data,<Some value>);
I managed to solve that issue .. it was an error in one line where i was doing << operation for the binary file.. we should not do that ..
But now I have one more issue... Can we write a string or a char* into a binary file.. and then read the same....
My code for write is
I managed to solve that issue .. it was an error in one line where i was doing << operation for the binary file.. we should not do that ..
But now I have one more issue... Can we write a string or a char* into a binary file.. and then read the same....
My code for write is
Now can we do the part which is in bold.. it is not working for me it gives me a segmentation fault while printing sToken in readDictBin.. It writes into a binary file properly.....
if you have only characters in the file it will read and display fine. but if you have multi-byte values like numbers, unicode then you have more work to do. what kind of file is this?
characters will be readable even if they are binary so dont worry about them.
this file contains characters as well as nos...... so i can c nos as binary format but characters as human readable format.... pls correct me if i m wrong... what i have understood is that .. since characters are 1 byte and we are writing it in binary format so it doesnt matter whether we write it in binary format or text format the size for characters will be the same... hence c++ doesnt allow characters or strings to be type casted and the stored when reading from binary file....
you dont have to do anything for characters but for numbers you have join them and for that you should be knowing if they are 2 bytes or 4 or these days can be 8 also.. int num = (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4; //for 4 bytes, its something like this
so read characters normally and print them but when you encounter numbers join them like this way:
easiest way will be write numbers at fixed byte length and then read these bytes directly in int or long and you will get it correct.