这个问题需要我从一个文件中读取一个标题,即基于位的压缩文件,以提取形成树所需的必要信息。通常头部看起来是这样的:“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);
}