我正在爲一個類的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