【问题标题】:Reading bytes from binary file with 2 byte buffer使用 2 字节缓冲区从二进制文件中读取字节
【发布时间】:2020-09-06 01:32:54
【问题描述】:

我目前正在尝试读取文件并计算 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

【问题讨论】:

  • 然后使用更大的数据类型...?
  • 当循环条件为i &lt; length 且length 为256 时,您如何期望i 超过255?
  • @mkrieger1 我想你错过了阅读代码,那个 for 循环只是用于初始化 values[] 。问题是如何扩展它。
  • 其实一点问题都没有。

标签: c file fopen file-handling fread


【解决方案1】:

首先,让我纠正你所说的话。到目前为止,您还没有打印 2 字节范围的频率。一般来说unsigned char是1字节(8位),你得到的结果也和我说的8 bits =&gt; 0 &lt;-&gt; 2^8 -1 =&gt; 0 &lt;-&gt; 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;
}

【讨论】:

  • 感谢澄清,我明天测试一下
  • 感谢它的工作,不得不将 u_int16_t 更改为 __uint16_t
  • 但是请注意机器的字节序。如果您希望文件中的 0x0001 为 1,那么上面的代码保证它是大端系统的一个,但如果您的系统是小端系统,您的系统会将文件数据 0x0001 解释为 256。您必须使用 netinet 的 htonl() 函数/in.h 将其转换为大端 stackoverflow.com/questions/12791864/… 查看此链接了解更多详情
猜你喜欢
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 2012-07-11
  • 1970-01-01
相关资源
最近更新 更多