mercredi 4 novembre 2015

How I can read a bin file in C and save the binary values in a unsigned int in a array?

hi i built a vm in c and want to read a bin file. This bin file has a structure, I can read them and compile this. but i dont know how i can save the value as unsigned int in a array :/

The binary file has this structure:

    4 Bytes -> Verify the format identifier
    4 Bytes -> version number
    4 Bytes -> number of instructions
    4 Bytes -> number of variables

n*4 bytes instructions

Here is my code

#include <stdio.h>
#include <stdlib.h>

unsigned  int buffer[300];

int main(int argc, char *argv[]) {

    FILE *file = fopen("Programm1.bin","r+b");

    printf("VM start...\n\n");

    if(file != NULL){

       if(1 == fread(&buffer, sizeof(unsigned int),1,file)){

            //printf("%c ", buffer[0]);
            //printf("%c ", buffer[1]);
            //printf("%c ", buffer[2]);
            //printf("%c ", buffer[3]);

            //printf("%x",buffer[4]);
        }
        else
        {
            printf("Der Header der Datei ist ungültig...");
            return(99);
        }
    }
    else
    {
        printf("Datei konnte nicht geöffnet werden...");
        return(99);
    }

    fclose(file);

return 0;
}

every instruction is 32 Bit => 4 Byte. The first Byte is the number of the instruction and the rest is the value

For Example:

0000 0001 0000 0000 0000 0000 0000 0011 => PUSH 3 (because PUSH is 1)

I want to save every instruction as unsigned int in a array.

I have the bin file and if I use hexdump -C i get this:

(For Information: The output is on head that mean it is from right to left)

enter image description here

The first 16 Byte are the header.

The rest are the instructions.

If I compile my Code in Clion IDE Then it doesn#t work but if I compile the code in gcc on the Terminal then I get this:

enter image description here

My Problems are that i dont know how i can save the instructions as unsigned int in my array and why Clion IDE it downst compile... -.-

(Maybe I can configured th Clion IDE to gcc compiler :/ )

but importent are the instructions to the array

thanks for help :)

Aucun commentaire:

Enregistrer un commentaire