我对 C++ 比较陌生,我正在尝试读取专有文件格式。我知道标头格式,并且创建了一个RTIHeader
包含必要字段的结构。
我的测试代码从文件中读取字节并将它们复制到与标头结构相同的内存空间中,从而有效地重构它。我的问题是每次我运行测试代码(只是调用构造函数)我都会得到不同的值!我的理论是我不完全理解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();
}