Reading a binary file bit by bit

后端 未结 6 1952
终归单人心
终归单人心 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 19:46

    For your problem you can see this demo program which read 2byte but actual information is only 12 bit.As well as this type of things are used it bit wise access.

    fwrite() is a standard library function which take the size argument as byte and of type int.So it is not possible exactly 12bit read.If the file you create then create like below as well as read as below it solve your problem.

    If that file is special file which not written by you then follow the standard provided for that file to read I think they also writing like this only.Or you can provide the axact where it I may help you.

    #include
    #include
    struct node
     {
       int data:12;
    
     }NODE;
    int main()
    {
       FILE *fp;
       fp=fopen("t","w");
       NODE.data=1024;
       printf("%d\n",NODE.data);
       fwrite(&NODE,sizeof(NODE),1,fp);
       NODE.data=0;
       NODE.data=2048;
       printf("%d\n",(unsigned)NODE.data);
       fwrite(&NODE,sizeof(NODE),1,fp);
       fclose(fp);
       fp=fopen("t","r");
       fread(&NODE,sizeof(NODE),1,fp);
       printf("%d\n",NODE.data);
       fread(&NODE,sizeof(NODE),1,fp);
       printf("%d\n",NODE.data);
       fclose(fp);
    }
    

提交回复
热议问题