读取和写入文件C ++

时间:2014-11-03 07:47:38

标签: c++ bit bitwise-operators huffman-code

我正在使用Huffman算法编写程序来压缩文本文件。我已经通过将打印ASCII字符打印到文件来测试我的程序,它工作正常。但是,现在我必须实现使用位,我的程序不起作用。好像我没有读或写正确的位。 这是我测试的结果: 在输入文件中,我将abc输入文件放入压缩它。然后我解压缩出来的是aaa。  下面是我如何读写位

的片段
class BitInput {
    istream& in;  // the istream to delegate to
    char buf;     // the buffer of bits
    int nbits;     // the bit buffer index

public:

BitInputStream(istream& s) : in(s), buf(0), bufi(8) { }
~BitInputStream //destructor
{
  delete in;
};

/** Read the next bit from the bit buffer.
 *  Return the bit read as the least significant bit of an int.
 */
int readBit(){
    int i;
    if(nbits == 8){
        buf = in.get();
        nbits = 0;
    }
    i = (1 & buf>>(7-nbits)); //This could be the problem, I'm not getting the writing bit
    nbits++;
    return i;
}

/** Read a char from the ostream (which is a byte)*/
int readChar(){
    int sum = 0;
    for(int i = 7; i>=0; i--) 
        sum = (sum*2) + readBit();
    return sum;
}

class BitOutput {
    ostream& out;  // the istream to delegate to
    char buf;     // the buffer of bits
    int nbits;     // the bit buffer index

public:

    BitOutput(istream& s) : in(s), buf(0), bufi(8) { }

    /* Write the least significant bit of the argument */
    void writeBit(int i){
        //Flush the buffer
        if(nbits == 8){
            out.put(buf);
            out.flush();
            nbits = 0;
            buf = 0;
        }
        buf = buf | (i<<(7-nbits)); //Did it write the right bit to ostream ?
        nbits++;
    }

    /** Write a char to the ostream (a byte) */
    void writeChar(int ch){
        for(int i = 7; i >= 0; i--) 
            writeBit((ch >> i) & 1);
    }

2 个答案:

答案 0 :(得分:0)

/* Write the least significant bit of the argument */
void writeBit(){
  int i; // <-- HERE
  //Flush the buffer
  if(nbits == 8){
   out.put(buf);
   out.flush();
   bufi = 0;
   buf = 0;
  }
 buf = buf | (i<<(7-nbits)); //Did it write the right bit to ostream ?
 nbits++;
}

您永远不会为i分配任何明智的价值。所以当你转移它时,你就会转移垃圾。

你可能想要:

/* Write the least significant bit of the argument */
void writeBit(int i){
  //Flush the buffer
  if(nbits == 8){
   out.put(buf);
   out.flush();
   bufi = 0;
   buf = 0;
  }
 buf = buf | (i<<(7-nbits)); //Did it write the right bit to ostream ?
 nbits++;
}

另外,向我们展示BitOutput的析构函数。那里也有很大的错误。

答案 1 :(得分:0)

您的代码:

    //Flush the buffer

    if(nbits == 8){
        out.put(buf);
        out.flush();
        bufi = 0;
        buf = 0;
    }

不将nbits重置为0.