【发布时间】:2012-01-05 15:16:41
【问题描述】:
在我当前的项目中,我有很多不同格式的二进制文件。其中有几个充当简单的档案,因此我正在尝试提出一种将提取的文件数据传递给其他类的好方法。
这是我当前方法的简化示例:
class Archive {
private:
std::istream &fs;
void Read();
public:
Archive(std::istream &fs); // Calls Read() automatically
~Archive();
const char* Get(int archiveIndex);
size_t GetSize(int archiveIndex);
};
class FileFormat {
private:
std::istream &fs;
void Read();
public:
FileFormat(std::istream &fs); // Calls Read() automatically
~FileFormat();
};
Archive 类主要解析存档并将存储的文件读入char 指针。
为了从Archive 加载第一个FileFormat 文件,我目前将使用以下代码:
std::ifstream fs("somearchive.arc", std::ios::binary);
Archive arc(fs);
std::istringstream ss(std::string(arc.Get(0), arc.GetSize(0)), std::ios::binary);
FileFormat ff(ss);
(请注意,存档中的某些文件可能是其他存档,但格式不同。)
读取二进制数据时,我使用BinaryReader 类,其功能如下:
BinaryReader::BinaryReader(std::istream &fs) : fs(fs) {
}
char* BinaryReader::ReadBytes(unsigned int n) {
char* buffer = new char[n];
fs.read(buffer, n);
return buffer;
}
unsigned int BinaryReader::ReadUInt32() {
unsigned int buffer;
fs.read((char*)&buffer, sizeof(unsigned int));
return buffer;
}
我喜欢这种方法的简单性,但我目前正在努力解决很多内存错误和 SIGSEGV 问题,我担心这是因为这种方法。一个例子是当我在一个循环中重复创建和读取档案时。它适用于大量迭代,但一段时间后,它开始读取垃圾数据。
我的问题是这种方法是否可行(在这种情况下我会问我做错了什么),如果不可行,还有什么更好的方法?
【问题讨论】:
-
你还没有展示 Archive 类的实现,我想用 std::ios::binary 打开 istream ?
-
我忘记了我在这里编写的代码中的 std::ios::binary 但它在我的版本中。 istream 是从 ifstream 构造的,并且该流使用 std::ios::binary 打开,如上所示。