簡體   English   中英

使用 2 字節緩沖區從二進制文件中讀取字節

[英]Reading bytes from binary file with 2 byte buffer

我目前正在嘗試讀取文件並計算 1 字節等效數字(0 到 255)的頻率。 我想對 2 字節等效數字(0 到 65535)做同樣的事情

我所擁有的簡化版本:

int length = 256; //any value 256>
long long values[length]
char buffer[length]
int i,nread;

fileptr = fopen("text.txt", "rb");

for (i=0; i<length; i++){ values[i]=0 }
while((nread = fread(buffer, 1, length, fileptr)) > 0){
   for(i=0;i<nread;i++){
      values[(unsigned char)buffer[i]]++;
   }
}

fclose(fileptr);

for(i=0;i<length;i++{ 
   printf("%d: %lld",i, values[i]); 
}

我現在得到的:

0: 21

1: 27

...

255: 19

我想要的是:

0: 4

1: 2

...

65535: 3

首先,讓我糾正你所說的。 到目前為止,您還沒有打印 2 字節范圍的頻率。 一般來說unsigned char是 1 個字節(8 位),你得到的結果也符合我所說的8 bits => 0 <-> 2^8 -1 => 0 <-> 255

要獲得 16 位范圍的頻率,您可以使用u_int16_t ,代碼如下

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main () {
    FILE* fp = NULL;

    /* Open file and setup fp */

    int *freq = (int*) calloc(65536, sizeof(int));

    u_int16_t value;

    for ( ; ; ) {
        if (read(fileno(fp), &value, sizeof(value)) < sizeof(value)) {
            /* Assuming partial reads wont happen, EOF reached or data remaining is less than 2 bytes */
            break;
        }

        freq[value] = freq[value] + 1;
    }

    for (int i = 0; i < 65536 ; i++) {
        printf("%d : %d\n", i, freq[i]);
    }

    return 0;
}

暫無
暫無

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

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