C一次读取4个字节 [英] C Read 4 bytes at a time

查看:379
本文介绍了C一次读取4个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制格式的文件,每个字长4个字节:

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

但是麻烦的是想出一种以前4个字节为操作码的方式来读取文件的方式,而后8至16个字节代表每行的后3个字。以下是我当前尚未使用的代码。

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);
}
}

我不确定如何获取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?

推荐答案

这将检查命令行是否包含文件名,然后尝试打开

while循环将一次读取文件16个字节,直到文件结束。

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;
}

这篇关于C一次读取4个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆