[英]Reading data from binary file
我正在尝试从二进制文件读取数据,并且出现问题。 我已经将其简化为最简单的情况,但仍然无法使用。 我是c ++的新手,所以我可能会做一些愚蠢的事情,但是,如果有人可以建议,我将非常感激。
码:
int main(int argc,char *argv[]) {
ifstream myfile;
vector<bool> encoded2;
cout << encoded2 << "\n"<< "\n" ;
myfile.open(argv[2], ios::in | ios::binary |ios::ate );
myfile.seekg(0,ios::beg);
myfile.read((char*)&encoded2, 1 );
myfile.close();
cout << encoded2 << "\n"<< "\n" ;
}
输出量
00000000
0000000000000000000000000000100011110000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Compression_Program(58221)malloc: *对象0x10012d错误:释放了未对齐的指针*在malloc_error_break中设置一个断点以进行调试
提前致谢。
不要将vector<bool>*
转换为char*
。 它没有做任何可预测的事情。
这里有两个错误:
vector<bool>
将向量强制转换为char *
并不是一件好事,因为向量是一个对象,并存储一些状态及其元素。
在这里,您可能覆盖了向量的状态,因此失败的析构函数。
也许您想转换向量的元素(保证将它们连续存储在内存中)。 但是另一个陷阱是vector<bool>
可能是实现优化的。
因此,您应该执行encoded2.reserve(8)
并使用myfile.read(reinterpret_cast<char *>(&encoded2[0]))
。
但是可能您想做其他事情,我们需要知道这里的目的是什么。
您正在阅读encoding2: myfile.read((char*)&encoded2, 1 );
。 这是错误的。 您可以阅读bool,然后将其放入encoding2
bool x;
myfile.read( &x, 1 );
encoded2[0] = x;
您正在覆盖std::vector
,而不应该这样做。 一个std::vector
实际上是一个指向数据数组的指针,以及一个保存其大小的整数(可能是size_t
)。 如果使用几乎随机的位覆盖这些位,则会发生数据损坏。
由于您只读取一个字节,因此就足够了:
char c;
myfile.read(&c, 1);
C ++语言没有提供一种有效的I / O方法来将位读取为位。 您必须成组读取位。 另外,在读取int位时,您还必须担心Endianess。
我建议使用一种老式的方法来分配缓冲区,读入缓冲区然后在缓冲区上进行操作。
const unsigned int BUFFER_SIZE = 1024 * 1024; // Let the compiler calculate it.
//...
unsigned char * const buffer = new unsigned char [BUFFER_SIZE]; // The pointer is constant.
unsigned int bytes_read = 0;
ifstream data_file("myfile.bin", ios::binary); // Open file for input without translations.
data_file.read(buffer, BUFFER_SIZE); // Read data into the buffer.
bytes_read = data_file.gcount(); // Get actual count of bytes read.
delete
缓冲区。 myfile.read((char*) &encoded2[0], sizeof(int)* COUNT);
或者您可以使用push_back();
int tmp;
for(int i = 0; i < COUNT; i++) {
myfile.read((char*) &tmp, 4);
encoded2.push_back(tmp);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.