简体   繁体   English

读取和指向函数中的结构

[英]Fread and pointer to structures in functions

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. 我正在使用标准结构地址使用fread读取信息,但退出功能后无法以某种方式访问​​信息。 So I tried adressing structure via pointers, but fread doesn't let me to do so. 所以我通过指针尝试了地址结构,但是fread不允许我这样做。 I've read that fread isn't designed to do it via pointers. 我读过fread并非旨在通过指针来实现。 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;
}

fread needs the address of a buffer. fread需要缓冲区的地址。 So in your second attempt, pass the address of fheader->sygnatura : 因此,在第二次尝试中,传递fheader->sygnatura的地址:

fread(&fheader->sygnatura,2,1,fp1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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