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.
You are going to need to have a one char buffer, and a count of the number of bits it holds. When that number reaches 8, you need to write it out, and reset the count to 0. You will also need a way to flush the buffer at the end. (Not that you cannot write 22 bits to a file - you can only write 16 or 24.
To write you need to use bit-wise operators such as & ^ | & << >>. make sure to learn what they do. For example to have 00100100 you need to set the first bit to 1, and shift it with the << >> operators 5 times. if you want to continue writing you just continue to set the first bit and shift it.
To write a binary file in C++ use write method. It is used to write a given number of bytes on the given stream, starting at the position of the "put" pointer. The file is extended if the put pointer is currently at the end of the file.
To write to a binary fileUse the WriteAllBytes method, supplying the file path and name and the bytes to be written. This example appends the data array CustomerData to the file named CollectedData. dat .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With