1

この問題では、ビットベースの圧縮ファイルであるファイルからヘッダーを読み取って、ツリーを形成するために必要な情報を抽出する必要があります。通常、ヘッドは次のようになります: "1g1o01s1 01e1h01p1r0000013\n" 1 はリーフ ノードを表し、0 はツリーを形成する必要がある場合を表します。ファイル内の文字数からヘッダー情報を分離する余分な 0 もあります。ツリーを作成してその内容を出力するものはすべて持っていますが、情報を読むのに苦労しています。コードを実行すると、出力の 1 つに含まれるべきではないリーフに「1」が含まれます。これは、ビットを取得したいときにバイトの処理に失敗していることを意味しますか?

コマンドライン出力

メインのコードは次のとおりです。

while((num = ReadBit(fp, 'b')))
{
    //printf("num = %c\n", num);
    if(num == '1')
    {
        letter = ReadBit(fp, 'c');
        printf("letter = %c\n\n", letter);
        new_node = CreateNode(letter);
        Push(&Fake, new_node);
        Onecount++;
    }
    if(num == '0')
    {
        First = Pop(&Fake);
        Second = Pop(&Fake);
        new_node = malloc(sizeof(LEAF));
        new_node-> rchild = First;
        new_node-> lchild = Second;
        Push(&Fake, new_node);
        Zerocount++;
    }

    if(Onecount == Zerocount)
    {
        break;
    }

}

ReadBit関数のコードは次のとおりです

int ReadBit(FILE *fp, char mode)
{  
unsigned char value;
unsigned static int count = 0;
unsigned static char letter = 0;
unsigned static char byte;
unsigned static int place;

    /* This is the bit mode, it will grab the first bit from the current byte and return it */
if(mode == 'b')
{
    if(count == 0)
    {
        fread(&byte, 1, 1, fp);
    }

    value = (((byte & (1 << (7 - count))) == 0) ? '0' : '1');
    count++;
    letter = byte << count;

    if(count == 8)
    {
        count =  0;
    }

    place = 8 - count;
}

/*This is "character" mode. It will grab enough bits in order to create a byte that will be a letter */
if(mode == 'c')
{
    if(count == 0)
    {
        fread(&letter, 1, 1, fp);
    }
    else
    {
        /* This will read in a new byte and add in as many bits as we need to complete a byte from the previously saved bits */
        fread(&byte, 1, 1, fp);
        value = letter + (byte >> place);
    }
}

return(value);
 }
4

0 に答える 0