将位写入 C++ 文件

Alf*_*rdo 4 c++ binaryfiles huffman-code

我正在研究霍夫曼编码,我已经用一个构建了字符频率表

std::map<char,int> frequencyTable;
Run Code Online (Sandbox Code Playgroud)

然后我构建了霍夫曼树,然后我以这种方式构建了代码表:

std::map<char,std::vector<bool> > codes;
Run Code Online (Sandbox Code Playgroud)

现在我将逐个字符地读取输入文件,并通过代码表对它们进行编码,但我不知道如何将位写入二进制输出文件。有什么建议吗?

更新:现在我正在尝试使用这些功能:

void Encoder::makeFile()
{
char c,ch;
unsigned char ch2;
while(inFile.get(c))
{
    ch=c;
    //send the Huffman string to output file bit by bit
    for(unsigned int i=0;i < codes[ch].size();++i)
    {
        if(codes[ch].at(i)==false){
            ch2=0;
        }else{
            ch2=1;
        }
        encode(ch2, outFile);
    }
}
ch2=2; // send EOF
encode(ch2, outFile);

inFile.close();
outFile.close();
}
Run Code Online (Sandbox Code Playgroud)

和这个:

void Encoder::encode(unsigned char i, std::ofstream & outFile)
{
int bit_pos=0; //0 to 7 (left to right) on the byte block
unsigned char c; //byte block to write

if(i<2) //if not EOF
{
    if(i==1)
        c |= (i<<(7-bit_pos)); //add a 1 to the byte
    else //i==0
        c=c & static_cast<unsigned char>(255-(1<<(7-bit_pos))); //add a 0
    ++bit_pos;
    bit_pos%=8;
    if(bit_pos==0)
    {
        outFile.put(c);
        c='\0';
    }
}
else
{
    outFile.put(c);
}
}
Run Code Online (Sandbox Code Playgroud)

但是,我不知道为什么,它不起作用,循环从未执行并且编码函数从未使用,为什么?

Jea*_*nès 5

您不能直接向文件写入单个位。读/写的I/O单位是字节(8位)。因此,您需要将 bool 打包成 8 位块,然后写入字节。例如,请参阅将位形式的文件写入 C 中的文件如何将单个位写入 C 中的文件。