I'm relatively new to C++ and I'm trying to read a proprietary file format. I know the header format, and I've created a struct RTIHeader
with the necessary fields.
My test code reads bytes from the file and copies them into the same memory space as the header struct, effectively reconstituting it. My problem is that every time I run the test code (just calling the constructor) I get a different value! My theory is that I do not fully understand memcpy
.
struct RTIHeader decode(char* memblock){
struct RTIHeader header;
memcpy(&header,&memblock,sizeof(RTIHeader));
return header;
}
RTIFile::RTIFile(const char* filename){
// open the file in binary input mode with the pointer at the end
std::ifstream file(filename,
std::ios::in |
std::ios::binary |
std::ios::ate);
std::ifstream::pos_type size;
char * memblock;
RTIHeader header;
// if the file didn't open, throw an error
if(!file.is_open()){
//TODO learn about C++ error handling
return;
}
// use pointer position to determine file size
size = file.tellg();
// read file
memblock = new char [sizeof(RTIHeader)];
file.seekg(0,std::ios::beg);
file.read(memblock,sizeof(RTIHeader));
header = decode(memblock);
std::cout << (unsigned int)header.signature[0] << "\n";
// still need to read the rest of the file
file.close();
}