Valrok
Valrok

Reputation: 1574

C Read 4 bytes at a time

I have a binary file that is in the following format where each word is 4 bytes long:

add arg1 arg2 arg3 // where in this example it would store the value of arg1+arg2 in arg3

I'm having trouble however figuring out a way to read the file in a way to where the first 4 bytes is an opcode, and the next 8 through 16 bytes represent the next 3 words per line. Below is my current code which I have not gotten working yet.

#define buflen 9000

char buf1[buflen];

int main(int argc, char** argv){
int fd;
int retval;

if ((fd = open(argv[1], O_RDONLY)) < 0) {
    exit(-1);
}
fseek(fd, 0, SEEK_END);
int fileSize = ftell(fd); 

for (int i = 0; i < fileSize; i += 4){
    //first 4 bytes = opcode value
    //next 4 bytes = arg1
    //next 4 bytes = arg2
    //next 4 bytes = arg3
    retval = read(fd, &buf1, 4);
}
}

I'm not sure how I can get 4 bytes at a time and then evaluate them. Could anyone provide me with some help?

Upvotes: 2

Views: 10798

Answers (1)

user3121023
user3121023

Reputation: 8286

This will check to see if the command line contains a filename and then tries to open the file.
The while loop will read the file 16 bytes at a time until the end of the file. The 16 bytes are assigned to opcode and args to process as needed.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int main( int argc, char *argv[])
{
    int fd;
    int retval;
    int each = 0;
    unsigned char buf[16] = {0};
    unsigned char opcode[4] = {0};
    unsigned char arg1[4] = {0};
    unsigned char arg2[4] = {0};
    unsigned char arg3[4] = {0};

    if ( argc < 2) {//was filename part of command
        printf ( "run as\n\tprogram filename\n");
        return 1;
    }

    if ((fd = open(argv[1], O_RDONLY)) < 0) {
        printf ( "could not open file\n");
        return 2;
    }

    while ( ( retval = read ( fd, &buf, 16)) > 0) {//read until end of file
        if ( retval == 16) {//read four words
            for ( each = 0; each < 4; each++) {
                opcode[each] = buf[each];
                arg1[each] = buf[each + 4];
                arg2[each] = buf[each + 8];
                arg3[each] = buf[each + 12];
            }
            //do something with opcode and arg...
        }
    }
    close ( fd);
    return 0;
}

Upvotes: 1

Related Questions