Hi,
i have this piece of code, the encoding function creates a file of binary 1's and 0's but since i am getting output in a text file, the result is shown as ASCII characters which appear as garbage. can anyone please tell me what should i add in the encode function, so that i get binary in the file rather than ascii. I am attaching the code.
/***************************************************************************
* Function : RiceEncodeFile
* Description: This routine reads an input file 1 character at a time and
* writes out a Rice encoded version of that file.
* Parameters : inFile - Name of file to encode
* outFile - Name of file to write encoded output to
* k - length of binary portion of encoded word
* Effects : File is encoded using the Rice algorithm with a k bit
* binary portion.
* Returned : TRUE for success, otherwise FALSE.
***************************************************************************/
int RiceEncodeFile(char *inFile, char *outFile, unsignedchar k)
{
FILE *fpIn; /* uncoded input */
bit_file_t *bfpOut; /* encoded output */
unsignedchar unary, binary; /* unary & binary portions */
unsignedchar mask; /* mask for binary portion */
int c;
/* open input and output files */
if (NULL == (fpIn = fopen(inFile, "rb")))
{
perror(inFile);
return FALSE;
}
if (NULL == outFile)
{
bfpOut = MakeBitFile(stdout, BF_WRITE);
}
else
{
if (NULL == (bfpOut = BitFileOpen(outFile, BF_WRITE)))
{
fclose(fpIn);
perror(outFile);
return FALSE;
}
}
mask = 0xFF >> (CHAR_BIT - k);// 0xFF * 3 =
/* encode input file one byte at a time */
while ((c = fgetc(fpIn)) != EOF)
{
/* compute the unary portion */
unary = (unsignedchar)c;
unary >>= k;
while (unary > 0)
{
/* write out unary worth of 1s */
unary--;
BitFilePutBit(1, bfpOut);
}
/* write an ending 0 */
BitFilePutBit(0, bfpOut);
/* binary portion */
binary = (unsignedchar)c & mask;
binary <<= (CHAR_BIT - k); /* right justify bits */
BitFilePutBits(bfpOut, &binary, k);
}
/* pad fill with 1s so decode will run into EOF */
BitFileFlushOutput(bfpOut, TRUE);
fclose(fpIn);
BitFileClose(bfpOut);
return TRUE;
}
You should use fread() to read a binary file opened with fopen(). In a binary file, markers like EOF and \n don't have special meaning, so you shouldn't expect them to have special meaning, which means don't use functions that imply specical meaning, like feof(), fscanf(), fgets(), fgetc() ...