Home > Enterprise >  How to copy the content of a binary file into an array
How to copy the content of a binary file into an array

Time:03-28

I am currently working on a chip-8 emulator and I have a method which loads in the program by copying a binary file into an array called 'memory'. However, it doesn't work as mentioned on the tutorial page and I'm a little bit confused. I've already researched this problem but I couldn't find anything helpful for my specific problem. Thank you, leon4aka

void chip8c::loadSoftware(char* filepath)
{
    FILE* fptr = NULL;
    u32 fsize;

    fptr = fopen(filepath, "rb"); // reading in binary mode

    if(fptr == NULL)
        printf("Error: invalid filepath");
    
    fseek(fptr, 0, SEEK_END);
    fsize = ftell(fptr);  // getting file size
    fseek(fptr, 0, SEEK_SET);
     
    for(int i = 0; i < fsize; i  )
        memory[i] = fptr[i]; // ! Does not work !

    fclose(fptr);
}

I tried copying the content of the file with a for-loop like shown above but it didn't work.

CodePudding user response:

You are not reading. You need to use a "read" function to read from the file. Please read here

Replace

memory[i] = fptr[i]; // ! Does work !

with

memory[i] = fgetc(fptr); // ! Does not work !
  • Related