0

I am working at program reading bitmap. The thing is I wrote everything in main and need to spread out code to functions. I am reading information using fread using standard structure adressing but I somehow cannot acces information after leaving function. So I tried adressing structure via pointers, but fread doesn't let me to do so. I've read that fread isn't designed to do it via pointers. But i cannot confirm it. And that's my question. How do I do it via pointers? And why my first try doesn't work outside function?

void odczyt_pliku_bmp(struct FileHeader fheader, struct MapHeader mheader, char *nazwa) {
    FILE *fp1;
    fp1 =fopen(nazwa,"rb");

    if(fp1)
    {
        fread(&fheader.sygnatura,2,1,fp1);
        //...


        printf("%d\n",fheader.sygnatura);//Checking. Everything seems right there

    }
    else
    {
        printf("Error");
    }
    fclose(fp1);
}

And main:

int main() {
    struct FileHeader fheader;
    struct MapHeader mheader;

    char nazwapliku, *wczyt_nazwa =&nazwapliku;
    printf("Podaj nazwe pliku bitmapy: ");
    scanf("%s",wczyt_nazwa);

    odczyt_pliku_bmp(fheader, mheader, wczyt_nazwa);
    printf("%d\n",fheader.sygnatura);// And there is random trash

    return 0;
}

Another try using pointers:

void odczyt_pliku_bmp(struct FileHeader *fheader, struct MapHeader *mheader, char *nazwa) {
    FILE *fp1;
    fp1 =fopen(nazwa,"rb");

    if(fp1)
    {
        fread(fheader->sygnatura,2,1,fp1);
        //...


        printf("%d\n",fheader->sygnatura);

    }
    else
    {
        printf("Error");
    }
    fclose(fp1);
}

Again main for second method:

int main() {
    struct FileHeader fheader;
    struct MapHeader mheader;

    char nazwapliku, *wczyt_nazwa =&nazwapliku;
    printf("Podaj nazwe pliku bitmapy: ");
    scanf("%s",wczyt_nazwa);

    odczyt_pliku_bmp(&fheader, &mheader, wczyt_nazwa);
    printf("%d\n",fheader.sygnatura);

    return 0;
}
dbush
  • 205,898
  • 23
  • 218
  • 273
Aghero
  • 13
  • 4
  • 2
    It will be easier to help you if you don't use Polish in code. – Everettss Jun 14 '16 at 20:02
  • `fread` reads data from the given stream into an array. In your code, however, the first argument to `fread` is a struct. This is problematic due to padding issue; a better approach is to read the file header into an array of `unsigned char`. – mw215 Jun 14 '16 at 21:32
  • A look at [this](http://stackoverflow.com/questions/37779302/fread-into-struct-reads-data-incorrectly/37780151) might be of help. – mw215 Jun 14 '16 at 21:33
  • Thank you all for your help. Yeah my bad. Next time I'll translate all names into english. Sorry for that – Aghero Jun 15 '16 at 20:41

1 Answers1

0

fread needs the address of a buffer. So in your second attempt, pass the address of fheader->sygnatura:

fread(&fheader->sygnatura,2,1,fp1);
dbush
  • 205,898
  • 23
  • 218
  • 273