Code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void foo(FILE *file, unsigned char value)
{
unsigned char bit;
for ( bit = 1 << (CHAR_BIT - 1); bit; bit >>= 1 )
{
fputc(value & bit ? '1' : '0', file);
}
}
int main(void)
{
const char filename[] = "file.txt";
FILE *file = fopen(filename, "wb");
if ( file )
{
const char text[] = "My question is why?\n";
size_t i;
for ( i = 0; i < sizeof text; ++i )
{
foo(file, text[i]);
}
fclose(file);
file = fopen(filename, "rb");
if ( file )
{
char buffer[CHAR_BIT + 1];
while ( fgets(buffer, sizeof buffer, file) )
{
fputc(strtol(buffer, NULL, 2), stdout);
}
fclose(file);
}
}
return 0;
}
/* my output
My question is why?
*/