简体   繁体   中英

Reading binary data from a file

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

int main()
{
    unsigned char **T;
    int i,j;
    int H[256];
    FILE *fp=fopen("Collines400300.ima","rb");
    T=(unsigned char**)malloc(300*sizeof(unsigned char*));
    for(i=0;i<400;i++);
    T[i]=(unsigned char*)malloc(400*sizeof(unsigned char));
    while(fp)
    {
        fread(T[i],1,400,fp);

    }


    for(i=0;i<256;i++)
    H[i]=0;


    for(i=0;i<400;i++)
    {
        for(j=0;j<300;j++)
        H[T[i][j]]++;
    }
    for(i=0;i<256;i++)
    printf("%d  ",H[i]);
    return 0;


}

I am attempting to read data of a gray scale image of length 300 and width 400 and load it to a 2D array. Then take that data and make a histogram out of it. I am not getting any compilation errors but I can't seem to read the information. Can anyone tell me what I am doing wrong? Thank you.

You have a couple of issues; surprised you didn't get a segfault.

//This line creates an array of char *'s of size 300
T=(unsigned char**)malloc(300*sizeof(unsigned char*));
//this line is bad... the ; at the end means this is the entire loop.  This is equivalent to i = 400;
    for(i=0;i<400;i++);
//this is not part of the foor loop, so you do T[400] which is outside both the bounds you may have wanted (400) and the bounds you set(300)
    T[i]=(unsigned char*)malloc(400*sizeof(unsigned char*));
    while(fp)
    {
        //this will just keep overwriting the same line.
        fread(T[i],1,400,fp);

    }

This should work a bit better:

int height = 300;
int width = 400;

T=(unsigned char**)malloc(height*sizeof(unsigned char*));
for(i=0;i<height;i++)
{
    if (feof(fp))
    {
       //handle error... could just malloc and memset to zero's
       break;
    }
    T[i]=(unsigned char*)malloc(width*sizeof(unsigned char*));
    fread(T[i],1,400,fp);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM