2015-09-14 67 views
0

我有一个二进制文件,在下面的格式,其中每个字是4个字节长:C了解4个字节是一次

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

遇到麻烦然而找出一种方法来读取文件在前4个字节是操作码的地方,接下来的8到16个字节代表每行下3个字。下面是我目前还没有工作的代码。

#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个字节,然后评估它们。任何人都可以提供一些帮助吗?

+1

4字节= 1个字。并且每行最多有4个字,但是某些操作码(如ex打印)可能只使用8个字节而不是全部16个 – Valrok

+0

1)如果您必须读取4个字节,为什么数组是'9000' ? 2)在for循环中,每次迭代都覆盖'buf'。 –

+0

哪个字节顺序是存储的数字?例如。 '1'可以存储为'00 00 00 01'或者'01 00 00 00'(或者别的什么) –

回答

1

这将检查命令行是否包含文件名,然后尝试打开文件。
while循环将一次读取文件16个字节,直到文件结束。这16个字节分配给操作码和参数以根据需要进行处理。

#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; 
} 
相关问题