digitaltos
digitaltos

Reputation: 85

Try to read data from binary file, failed to put it in struct

Edited the code to be more simpler and without the linked list pointer.

Here is my struct

typedef struct megye
{ 
    int megye;
    int hektar1_min;
    int hektar1_max;
    int hektar1_tam;
    int hektar2_min;
    int hektar2_max;
    int hektar2_tam;
    int hektar3_min;
    int hektar3_tam;

}megye;

and I have tried without the "struct _megye *next;" line too.

Here is my code:

int main()
{
    FILE *fb;
    megye*p;

    p=(megye*)calloc(8,sizeof(megye));

    fb=fopen("tamogatas.dat", "rb");
    if (fb==NULL)
    {
        printf("couldn't open file");
    }
    while (fread(p, sizeof (megye), 7, fb))
    {
        printf("%d\n", p->megye);
    }
    fclose(fb);
    _CrtDumpMemoryLeaks();
    free(p);
    return 0;
}

Here is a line from the text file which I converted to a binary file which I use here:

1 50 100 2 100 200 4 200 6

My goal is to put every number in a line to an int in the struct.

The program runs, puts random numbers in the struct (always changing, long numbers from 6 digits to about 13-14). The debugger says that he fread function reads the file's first line (fread's _base string) but it simply doesn't put it in the struct. What do I have to do to get my numbers into the struct?

Please be simple, I haven't slept in two days :(

Edit: I have to do it with a binary file because it's homework.

Upvotes: 0

Views: 450

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40155

example of one record read/write to binary file

int main(){
    FILE *fb;
    megye orig = {1, 50, 100, 2, 100, 200, 4, 200, 6 };
    megye *p;

    fb=fopen("megye.dat", "wb");
    fwrite(&orig, sizeof(megye), 1, fb);//1 record of struct megye to binary file of megye.dat
    fclose(fb);

    p=(megye*)calloc(1, sizeof(megye));//memory ensure 1 record of struct megye

    fb=fopen("megye.dat", "rb");
    if (fb==NULL)
    {
        printf("couldn't open file");
    }
    while (1==fread(p, sizeof(megye), 1, fb))//1 :read number of record
    {
        printf("%d %d ...\n", p->megye, p->hektar1_min);
    }
    fclose(fb);
    //_CrtDumpMemoryLeaks();
    free(p);
    return 0;
}

Upvotes: 1

Related Questions