0

我想将一个结构数组放入一个文件中,并将一个整数放入同一个文件中(我想对数组使用 fwrite() )。当我尝试阅读它时,似乎出现了问题。我是 C 的新手,所以也许你可以向我解释它是如何工作的。提前致谢。

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

typedef struct Data{

    char street[40];
    char building[10];
    char email[30];
    unsigned long long number;

}Data;

int main(){

    Data data[3];
    Data output[3];
    int size = 2;
    int sizeout;
    // putting something inside
    strcpy(data[0].building, "11");
    strcpy(data[0].email, "a@a.a");
    data[0].number = 37068678102;
    strcpy(data[0].street, "Street1");

    strcpy(data[1].building, "21");
    strcpy(data[1].email, "b@b.b");
    data[1].number = 37068678432;
    strcpy(data[1].street, "Street2");

    //writing into file (I want to use "wb")
    FILE *write;
    write = fopen("temp.bin","wb");
    //if I understand correctly, fprintf is the way to put in an integer
    fprintf(write,"%d",size);
    //putting array in
    fwrite(data,sizeof(Data),2,write);
    fclose(write);



    FILE *read;
    fseek(read, 0, SEEK_SET);

    read = fopen("temp.bin","rb");
    //gettinf the int out
    fscanf(read,"%d",&sizeout);
    //getting array out
    fread(output,sizeof(Data),2,read);
    fclose(read);

    //printing what I got
    for(int i = 0; i < sizeout; ++i){
        printf("First struct: %s %s %s %llu\n", output[i].building, output[i].email, output[i].street, output[i].number);
    }
    return 0;
}
4

1 回答 1

0

这是您的代码,但更简洁。这家伙说的是真的

您之前调用fseek了读取指针fopen

但这也不是必需的,因为当您打开文件时r,指针将始终位于第一个位置,无论

#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#define doc "doc.bin"

typedef struct Data{

    char street[40];
    char building[10];
    char email[30];
    unsigned long long number;

}Data;

int sizeofdata =  sizeof(Data);


int main(){



FILE *f;

f = fopen(doc, "wb"); //if you want to open it in w remember that all that is contained with in will be erased , i recomend a+b

      Data data[3];
    Data output[3];
    int size = 2;
    int sizeout;
    // putting something inside
    strcpy(data[0].building, "11");
    strcpy(data[0].email, "a@a.a");
    data[0].number = 37068678102;
    strcpy(data[0].street, "Street1");

     fwrite(&data, sizeofdata,1, f);//the one represents the quantitie of regiesteres you wanna imput , you can make it a variable

     fclose(f);


     if ((f=fopen(doc,"rb"))!=NULL){//this makes for a cleaner solution it will be simpeler in the long run
            while (!feof(f)) {
            fread(&output, sizeofdata,1, f);
            if (!feof(f)){
               printf("First struct: %s %s %s %llu\n", output[0].building, output[0].email, output[0].street, output[0].number);
            }
}
     }
于 2020-12-03T22:49:22.400 回答