2015-09-14 53 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; 
} 
相關問題