fwrite()没有将任何内容写入文件 - C

时间:2015-12-19 01:37:23

标签: c encoding bit-manipulation binaryfiles fwrite

我正在编写一个Huffman代码来压缩和解压缩文件。我目前处于将Huffman树中每个字符的“路由”转换为int并将其写入二进制文件的阶段。这就是我所拥有的:

int ConversionToBinary ( FILE *binaryFile, char *string, int *currentBit, int *bitCounter ) {
    int x;
    int stringLength;
    stringLength = CalculateStringLength ( string );
    short int i;
    for ( i = 0; i < stringLength; i++ ) {
        x = ConversionToNumber ( string [ i ] );
        *currentBit = x | 1 << *contadorDeBits;
        *bitCounter++;
        if  ( *bitCounter == MAX_NUMBER_OF_BITS ) {
            fwrite ( currentBit, 1, sizeof ( int ), binaryFile );
            *currentBit = 0;
            *bitCounter = 0;
        }
    }
}

该部分代码基于我在this thread中找到的内容:

这是调用ConversionToBinary的函数的相关部分,以防万一:

currentBit = bitCounter = 0;
EmptyString ( string );
while ( ( character = fgetc ( textFile ) ) != EOF ) {
    auxElement = SearchInHashTable ( HashTable, character );
    strcpy ( string, auxElement -> route );
    ConversionToBinary ( binaryFile, string, &currentBit, &bitCounter );
    EmptyString ( string );
}

如您所见,我将所有相关数据存储在哈希表中,以便我可以从那里轻松检索它。

事情是,当我打电话给 ConversionToBinary 时,它没有写任何内容,我不知道为什么会这样。我已经检查过是否满足条件*( bitCounter == MAX_NUMBER_OF_BITS),但逻辑上它应该是,所以即使实际的转换是错误的,至少它应该写的东西在我的文件中,但它没有。

我目前已经没有想法,我需要一些帮助。

1 个答案:

答案 0 :(得分:0)

I was checking why that operation went the way it did. If I'm not getting this wrong, it has to do something with the operator precedence. According to this, the operators * and ++ have the same precedence, and they are evaluated from right to left. So when i was doing this: *bitCounter++, instead of incrementing said value, i was setting its memory address one block further away, so when I asked for value it was showing me the value stored in said address. Was that the error i was committing more or less? – ShadowGeist

That's almost right, except that *bitCounter++ yields the value stored at the address as it was before the increment, i. e. at the original bitCounter in the first loop cycle, at the next address in the second cycle, and so on.