我正在为一个类的C++文本文件压缩程序工作。 我有一切工作,除了能够以二进制模式输出到文件。 我使用:二进制输出C++
FILE* pFile;
pFile = fopen(c, "wb");
为了打开文件以二进制方式写,
bool Buffer[8] = { 0, 0, 0,0, 0,0, 0,0 };
进出口使用的bool的缓冲区(初始化为全0)来存储1和0至存储每个字节的数据,直到我使用fwrite。
vector<bool> temp2 = bitstring[temp];//bitstring refers to a vector in a map at key [temp]
for (vector<bool>::iterator v = temp2.begin(); v != temp2.end(); ++v)
{
if (j < 8)//To create an 8 bit/byte buffer
{
if (*v == 1)//Checks the vector at that position to know what the bit is.
Buffer[j] =1;//sets the array at 'j' to 1
else
Buffer[j] =0 ;//sets the array at 'j' to 0
j++;
}
else //once the Buffer hits 8 it will print the buffer to the file
{
fwrite(Buffer,1,sizeof(Buffer), pFile);
clearBuffer(Buffer);//Clears the buffer to restart the process.
j = 0;
}
}
的(矢量迭代器)正在经历被分配给一个特定的字符,基本上表示所述字符的唯一二进制串的bool的向量。我的问题是,不是在缓冲区中输出为二进制文件,而是在二进制模式下输出本质上的ASCII字符,而不是将数字输出为二进制。最终导致文件的大小超过了它的需求。我怎么能改变缓冲区,只是输出位。我被告知使用按位运算符,但我无法找到有关在C++中实现这一点的非常多文档。任何帮助表示赞赏,并
'的std :: vector的 '并不涉及连续的位序列。 ['std :: bitset <>'](http://en.cppreference.com/w/cpp/utility/bitset)确实有用,但可能不适合您的用例,因为它不支持可变长度比特流。 –
2014-10-06 19:47:05
注意:你有一个逻辑错误,使用:for(...){if(index == buffer_size {write_buffer(); index = 0;} insert_into_buffer();} write_buffer_if_index_is_not_zero; – 2014-10-06 19:58:45
注意:std :: vector可能首先是错误的选择 –
2014-10-06 20:16:03