使用位操作解码文件

时间:2014-09-30 21:09:12

标签: c binary bit-manipulation decoding bit-shift

不断得到分段错误,我无法解决这个问题。如果程序运行" encodeFile" - 函数,程序应该能够逐字符地读取输入文件并压缩2位值的字符。然后,这些值将打印在输出文件中。我对这门语言很陌生。我该如何解决这个问题?

//The function
void encodeFile(char *fpInputfile,char *fpOutputfile)
{
        FILE *fileInput = fopen(fpInputfile, "r");
        FILE *fileOutput = fopen(fpOutputfile, "w");

        if (!fileInput || !fileOutput){
            printf("ERROR MESSAGE: can not open the selected file \n");
            exit(1);
        }

        char symbols[4];
        char encodeB[4] = {0x00, 0x01, 0x02, 0x03};
        size_t c = fread(symbols, sizeof(char), 4, fileInput);

        while (c != 0){
            int i = 0;
            int j = 0;
            char temp = 0;
            while (c > 0){

                if (symbols[j] == ' '){
                    temp = encodeB[0];
                }
                else if (symbols[j] == ':'){
                    temp = encodeB[1];
                }
                else if (symbols[j] == '@'){
                    temp = encodeB[2];
                }
                else if (symbols[j] == '\n'){
                    temp = encodeB[3];
                }
                else{
                }
                j++;
                i |= temp << (c *2);
                c++;
            }
            //c = fread(symbols, sizeof(char), 4, fileInput);
            //fwrite(&temp, 1, 1, fileOutput);
        }
        fclose(fileInput);
        fclose(fileOutput);

    }

1 个答案:

答案 0 :(得分:0)

while (c > 0){
   ...
   c++;
}

这将导致无限循环。分段错误来自阅读符号[4],这是一种访问冲突。

如果您想使用这种语言,我强烈建议您学习如何在调试器中单步调试代码。祝你好运!