As part of an assignment, I need to read data from a binary file which consists of int, char datatypes of data. This binary file is divided into records 96 bytes each. I am trying to reading these 96 bytes into a char buffer and then trying to split them according to info I have. But I am getting nothing when trying to get int values from the buffer. Can you help me in this?
#include<iostream>
#include<fstream>
#include<cstdio>
using namespace std;
int main()
{
char buffer[100];
char *p;
char temp[10];
int val;
fstream ifs,ofs;
ifs.open("write.bin",ios::binary);
if(ifs.read(buffer,96))
{
cout << "READ" << endl;
}
p = buffer;
memcpy(temp,buffer,4);
cout << temp << endl;
val = atoi(temp);
cout << val << endl;
}
I used strncpy also in place of memcpy.
The output is 0 for val and blank for temp.
atoitransforms strings (char arrays) into integers. So something like"42"would return the integer42. The way your question is written, it sounds like the integers are simply stored as binary in the textfile.A simple cast of the buffer pointer to the desired type plus a dereference should do:
If you want to use
memcpy, there’s no need to copy to a char array, you can copy directly to an integer address:With plain C (not C++) this would be:
I chose
uint32_tas a data type, because it is guaranteed to have 32 bits/4 bytes –intmight, on some platforms/compilers, be of different size.