I found some codes about converting a binary text from a binary file to text file. But my purpose is to convert a binary text from a binary file to string variable because I have to do some string operations after conversion. Here is the code that I found.
FILE *binaryFile = fopen("binary.dat", "rb");
FILE *output_file = fopen("output.txt", "w");
unsigned char byte = 0;
int bits = 0;
for (;;)
{
char buffer[1024];
int len = fread(buffer, 1, sizeof(buffer), binaryFile);
// if there was a read error or EOF, stop
if (len <= 0)
break;
for (int i = 0; i < len; ++i)
{
switch (buffer[i])
{
// if a binary 1, turn on bit zero
case '1':
byte |= 1;
break;
// if a binary 0, do nothing
case '0':
break;
// if anything else, skip
default:
continue;
}
// increment the counter, if we dont yet have 8 bits
// shift all the bits left by one
if (++bits < 8)
byte <<= 1;
else
{
// write out the complete byte
fwrite(&byte, 1, 1, outputFile);
// reset for the next byte
bits = 0;
byte = 0;
}
}
}
// write out any remaining data if the input was not a multiple of 8 in length.
if (bits) {
fwrite(&byte, 1, 1, outputFile);
}
fclose(xmlFile);
As you can see fwrite method is writing to file. It is working but I want to store it in a string variable.
I tried to find a direct solution but I can't find it. The best solution to this problem is converting to file then read that file and store it to string variable. But I can't do that.
Declare an output buffer array and index:
Replace:
FILE *output_file = fopen("output.txt", "w");
with:
unsigned char output_buffer[MAX_BUF] = "";
int output_index = 0;
Then replace
fwrite(&byte, 1, 1, outputFile);
with:
output_buffer[output_index++] = byte;
You'll need to declare the MAX_BUF
macro with the maximum possible string. If you can't specify a maximum, you'll need to use malloc()
and realloc()
to grow the string dynamically.