【发布时间】:2013-07-01 17:22:21
【问题描述】:
我正在尝试从文件中读取二进制数据,这是我的文件结构:
#define SIGNATURE_LENGTH 3
#define VERSION_LENGTH 2
#define DATACOUNT_LENGTH 4
#define COMPRESS_LENGTH 1
#define FORMAT_LENGTH 2
#define DATALENGTH_LENGTH 4
const unsigned char resSignature[SIGNATURE_LENGTH] = { 0x52, 0x45, 0x53 };
const unsigned char resVersion[VERSION_LENGTH] = { 0x01, 0x00 };
const unsigned char isCompressed[COMPRESS_LENGTH] = { 0x01 };
const unsigned char notCompressed[COMPRESS_LENGTH] = { 0x00 };
// Data Formats:
const unsigned char dataUnknown[FORMAT_LENGTH] = { 0x00, 0x00 };
const unsigned char dataXML[FORMAT_LENGTH] = { 0x01, 0x00 };
// Define header structure for resource file
struct ResHeader
{
unsigned char signature[SIGNATURE_LENGTH];
unsigned char version[VERSION_LENGTH];
};
// Define data structure for resource file
struct ResData
{
unsigned char compressed[COMPRESS_LENGTH];
unsigned char dataFormat[FORMAT_LENGTH];
unsigned char dataLength[DATALENGTH_LENGTH];
unsigned char *data;
};
我的班级使用:
std::fstream File;
// Resource file makeup
ResHeader header;
unsigned char dataCount[DATACOUNT_LENGTH];
// Vector to contain resource file data
std::vector<ResData> ResourceData;
当我尝试读取文件时程序崩溃:
int ResourceFile::LoadFile()
{
File.open("blah.dat", std::ios::in | std::ios::binary);
// Read header
File.read((char*) header.signature, SIGNATURE_LENGTH);
File.read((char*) header.version, VERSION_LENGTH);
if(!VerifyHeader())
{
File.close();
return HEADER_INCORRECT;
}
File.read((char*) dataCount, DATACOUNT_LENGTH);
long fileCount = unsignedCharArrayToLong(dataCount);
for(long i = 0; i < fileCount; ++i)
{
ResData tmp;
File.read((char*) tmp.compressed, COMPRESS_LENGTH);
File.read((char*) tmp.dataFormat, FORMAT_LENGTH);
File.read((char*) tmp.dataLength, DATALENGTH_LENGTH);
File.read((char*) tmp.data, unsignedCharArrayToLong(tmp.dataLength));
ResourceData.push_back(tmp);
}
File.close();
return SUCCESS;
}
程序崩溃就行了:
File.read((char*) tmp.data, unsignedCharArrayToLong(tmp.dataLength));
文件中数据的长度为282,也就是读入tmp.dataLength;所以这个数字是准确的。数据也使用easy zlib压缩:http://www.firstobject.com/easy-zlib-c++-xml-compression.htm
任何关于我做错了什么或我可以做得更好的建议/帮助将不胜感激。 谢谢。
【问题讨论】:
-
检查你的文件是否为空
-
检查
tmp.data是否为空(或未定义)... -
unsignedCharArrayToLong(tmp.dataLength)的结果是什么?另外,你在哪里分配data? -
if(!File) 不会出错,if(tmp.data == NULL) 也不会出错
-
通过“不分配” tmp.data,它指向内存中的任意位置。由于在 32 位内存架构中大约有 40 亿个这样的位置,并且您的程序最多占用几兆字节 - 其中大部分是不可写的,因此您的“任意”内存地址的可能性大约为千分之一“坏”,导致它崩溃。这有点像在背后扔飞镖。如果你很幸运,你会击中飞镖板,如果你非常幸运,你会击中 20 高音。大多数时候,你不会击中墙以外的任何东西......