Francesco B. Francesco B. - 8 days ago 5
C Question

Writing bits to a file in C

I have this string: "101"
I want to write it to a file, in C, not as text: "101" and so 8 bits x char. but directly use the string as bits: the bit "1", the bit "0" and the bit "1", so that the file will be of 3 bits.

Is it possibile?
I searched on the web and I tried doing this:

char c[25] = "101";
FILE *binFile = fopen("binFile.bin", "wb");
int x = atoi(c);
fwrite(&x, sizeof(x), 1, binFile);


But at the end, when I verify files's bytes, Windows says me that it is 4bytes file! And not 3bits!

How can I do this, if it is possible? Thanks a lot.

Jon Jon
Answer

All filesystems┬╣ deal with files in terms of bytes (and allocate storage space with a much larger granularity, 512 bytes at a time minimum). There's no way you are going to get a file that is 3 bits long.

The best you can do is use up one whole byte but ignore 5 of its bits. To do that (assuming that the number is always going to fit into a byte), convert the input string to an integral type:

long l = strtol(c, 0, 2);

Then get its least significant byte:

unsigned char b = l & 0xffl;

And write it to the file:

fwrite(&b, 1, 1, binFile);

┬╣ Well, maybe not all. There might be some researchers somewhere that experiment with bit-sized filesystems. I wouldn't know.