c++ - 从二进制文件读取

标签 c++

我正在尝试计算二进制文件中零和一的数量。问题是,我得到正确的答案。的零,但出来等于没有。的零。 我正在做的是逐个读取文件 char 。由于最多可以有 256 个字符,我将结果存储在一个临时数组中,同时包含 0 和 1,如果再次出现字符,则从那里检索。

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
void func(int* a1 ,int* a2)
{
    for(int i=0;i<256;i++)
    for(int j=0;j<8;j++)
    {
        if( (i & 1) ==1 )
        {
            a1[i]+=1;
        }
        else if( (i & 1) ==0 )
        {
            a2[i]+=1;   
        }
        i>>1;
    }
}
int main()
{
    int zero[256];
    int one[256];
    int tzero[256];
    int tone[256];
    for(int i=0;i<256;i++)
    {
        zero[i]=0;
        one[i]=0;
        tzero[i]=0;
        tone[i]=0;
    }
    func(tone,tzero);
    FILE* input;
    FILE* output;
    output=fopen("ascii.txt","w");
    input=fopen("one.bin","r");
    int c;
    while((c=fgetc(input))!=EOF)
    {
        fprintf(output,"%d\n",c);
        zero[c]+=tzero[c];
        one[c]+=tone[c];
    }
    int zeroes=0;
    int ones=0;
    for(int i=0;i<=255;i++)
    {
        zeroes+=zero[i];
        ones+=one[i];
    }
    cout<<"zeroes:"<<zeroes<<endl;
    cout<<"ones:"<<ones<<endl;
    fclose(input);

    fclose(output);

}

最佳答案

计算 0 和 1 的循环破坏了 c 的值

c >>= 1;

完成所有八次移位后,c 始终为零,因此以下代码递增错误计数:

// The value of c is always zero
tzero[c]=z;
tone[c]=o;
one[c]+=tzero[c];
zero[c]+=tzero[c];

你应该在比特计数循环之前保存c的值,并在循环结束后恢复它。

更好的是,预先计算 tzero[]tone[] 的值,而无需等待它们出现在文件中。这将使您的主循环主体非常短和干净:

while((c=fgetc(input))!=EOF) {
    one[c] += tzero[c];
    zero[c] += tzero[c];
}

关于c++ - 从二进制文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18831658/

相关文章:

c++ - 在另一个模板基类中实现抽象基类函数

c++ - 尽管资源存在,但 FindResource() 函数失败

c++ - C++程序员学习Objective-C的建议

c++ - 智能指针 - 为什么使用它们,以及使用哪个?

c++ - 链表中的结构

c++ - 使用套接字c++ eclipse删除数组

c++ - Visual Studio 调试器显示 native 类型的错误值

C++ - 清理整数输入

C++, Lint : lint does not discover taking reference to a local variable and passing it on to another function

c++ - 我如何在 python 中取消引用? (使用openCV进行图像处理)