Reading a binary file bit by bit

后端 未结 6 1963
终归单人心
终归单人心 2020-12-16 19:35

I know the function below:

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

It only reads byte by

6条回答
  •  死守一世寂寞
    2020-12-16 20:12

    I've implemented a couple of methods to read/write files bit by bit. Here they are. Whether it is viable or not for your use case, you have to decide that for yourself. I've tried to make the most readable, optimized code i could, not being a seasoned C developer (for now).

    Internally, it uses a "bitCursor" to store information about previous bits that don't yet fit a full byte. It has who data fields: d stores data and s stores size, or the amount of bits stored in the cursor.

    You have four functions:

    • newBitCursor(), which returns a bitCursor object with default values
      {0,0}. Such a cursor is needed at the beginning of a sequence of read/write operations to or from a file.
    • fwriteb(void *ptr, size_t sizeb, size_t rSizeb, FILE *fp, bitCursor *c), which writes sizeb rightmost bits of the value stored in ptr to fp.
    • fcloseb(FILE *fp, bitCursor *c), which writes a remaining byte, if the previous writes did not exactly encapsulate all data needed to be written, that is probably almost always the case...
    • freadb(void *ptr, size_t sizeb, size_t rSizeb, FILE *fp, bitCursor *c), which reads sizeb bits and bitwise ORs them to *ptr. (it is, therefore, your responsibility to init *ptr as 0)

    More info is provided in the comments. Have Fun!

    Edit: It has come to my knowledge today that when i made that i assumed Little Endian! :P Oops! It's always nice to realize how much of a noob i still am ;D.

    Edit: GNU's Binary File Descriptors.

提交回复
热议问题