簡體   English   中英

C 將二進制文件讀入緩沖區

[英]C Read binary file to a buffer

我正在嘗試創建一個可以讀取二進制文件的簡單 VM,按照二進制文件中的說明進行操作(每條指令 4 個字 - 32 位),然后在遵循所有指令后輸出結果。

我目前處於我項目的第一階段,並且正在嘗試使用 fread/fopen 將我的文件內容讀入緩沖區。 在大多數情況下,代碼類似於 fread 上為 cplusplus.com 提供的示例,但是我想找到一種方法將我的文件一次分成 4 個單詞。 我以前從未在如此低的級別工作過,並且在確定我是否正確執行此操作時遇到了問題,並希望這里有人可以幫助我確保我正確地將文件分解為 4 個單詞。

FILE * pFile;
long lSize;
unsigned char * buffer;
size_t result;

  pFile = fopen ( "test.bin" , "rb" );

  if (pFile==NULL) {fprint("error, file null")}

  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (unsigned char*) malloc (sizeof(unsigned char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer, 4,lSize,pFile); //The error is here, if I use 1 instead of 4 there is no error output but I am not sure this would properly break the file into 4 words read at a time.
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
   printf("%ld\n",lSize);

現在,當我運行它時,我收到一個錯誤,除非我將注釋行中的數字更改回 1。

將二進制文件表示為緩沖區是您的操作系統可以為您做的事情; mmap的手冊頁在 C89 中有一個工作示例(所以它是古董):

       fd = open(argv[1], O_RDONLY);

...

       if (fstat(fd, &sb) == -1)           /* To obtain file size */
           handle_error("fstat");

       offset = atoi(argv[2]);
       pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);
           /* offset for mmap() must be page aligned */

...

       if (argc == 4) {
           length = atoi(argv[3]);
           if (offset + length > sb.st_size)
               length = sb.st_size - offset;
                   /* Can't display bytes past end of file */

       } else {    /* No length arg ==> display to end of file */
           length = sb.st_size - offset;
       }

       addr = mmap(NULL, length + offset - pa_offset, PROT_READ,
                   MAP_PRIVATE, fd, pa_offset);
       if (addr == MAP_FAILED)
           handle_error("mmap");

現在, addr指向包含進程地址空間中輸入文件的內存區域。

這將節省您在開始處理之前閱讀整個文件的時間,因為您的操作系統可以自動僅讀取您實際訪問的文件部分,而無需多說。

此外,由於您正在編寫 VM(無論這對您意味着什么!),您應該了解典型的進程內存結構,因此學習mmap作用是一個很好的練習。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM