File content is always binary using 8-bit (byte) as smallest unit. What kind of data is represented depends on the file type and must be handled accordingly by the application when reading and writing the file.
The
fgetc - C++ Reference[
^] function returns a single byte read from the file as an
int
. The reason for returning an
int
instead of a byte type like
char
or
unsigned char
is that an additional return value for errors and end of file is required (
EOF
).
So you don't need any conversion. But you may need to interpret the data to prepare it for usage or just printing it out.
If you have no information about the file type, you can print the binary content:
#include <stdio.h>
int main(int argc, char* argv[])
{
int c;
FILE *f;
if (argc > 1)
{
f = fopen(argv[1], "rb");
if (f)
{
do
{
c = fgetc(f);
if (EOF != c)
printf("%02X ", c);
} while (EOF != c);
fclose(f);
}
}
printf("\n");
return 0;
}
If you want to print each byte as bit sequence you have to write a corresponding function (call this instead of the
printf
function in the above example):
void print_byte_as_bits(int byte_value)
{
int i;
if (byte_value >= 0 && byte_value < 256)
{
for (i = 0; i < 8; i++)
{
printf("%c ", (byte_value & 0x80) ? '1' : '0');
byte_value <<= 1;
}
}
else
printf("[Not a byte: %X]", byte_value);
}