简体   繁体   中英

Can't write the struct to a file C++

I can't put the information I write on the struct to a file, this is the part of the code that I have the functions, on main I only have a switch to choose which functions to use. I'm sorry that the code is written in Portuguese, I can translate it if needed.

typedef struct Pessoa{
   char nome[30];
   int idade;
}pessoa;

FILE *arquivo;
pessoa p1[3];

int i=0;

void inserir(){
    do{
        cout<<"\nInsira o nome: ";
        cin.clear();
        cin.sync();
        cin.getline(p1[i].nome,sizeof(p1[i].nome));

        cout<<"\nInsira a idade: ";
        cin.clear();
        cin.sync();
        cin>>p1[i].idade;

        i++;
    }while(i<3);
}//inserir

void carregar(){
                fflush(stdin);
                if((arquivo = fopen("contatos.dat","wb+")) !=NULL){
                        cout<<"It enters the write part"<<endl;//just checking if it enters the write part
                        fwrite(&p1,sizeof(p1),1,arquivo);
                }

                else{
                    cout<<"Erro: arquivo nao pode ser aberto";
                }
}//carregar

Please note that writing entire objects (or structs in this case) to file in binary form is somewhat dangerous. You should write each member of struct separetely to avoid padding (which may(or not) be one of reasons why your binary files become broken) and type size on different machines. Keep in mind that the data should be formatted (serialized) in certain order (Little/Big Endian) as a target device might operate on different endianness.

The simplest way might be by dividing your data into smaller chunks (chars) by shifting bits and then writing it to a buffer.

@edited with example

A simple example:

    //a function that serializes 32-bit unsigned int i to buffer buff
    void uint32toLE(const uint32_t &i, uint8_t* buf)
    {
        //buf needs to be provided as pointer to char array,
        //In my version I am incrementing pointer, therefore I suggest
        //assigning address to a new pointer: char* temp=buf and replace
        //buf++ with temp++ OR pass a copy of pointer

        //buff++ represent post-incrementation, 
        // int* ptr; create pointer,
        //*(ptr)=y - dereference ptr (use value not address) and assign value y 
        *(buf++)= (i&0x000000ff); //bit i AND 255
        *(buf++)= (i&0x0000ff00) >> 8; //i AND 65280 then shift value right by 8 bits
        *(buf++)= (i&0x00ff0000) >> 16; // i AND 16711680 then shift
        *(buf++)= (i&0xff000000) >> 24; // i AND 4278190080 then shift too
    }

The results of above is representation of 32-bit value in 8bit chunks. This somewhat protects our binary data from breaking (so long we are able to access 8-bit chars on our machine).

If you want to serialize entire objects, you need to provide functions that will serialize each individual member.

@edit

It's worth looking at serialization of binary data if you want to learn how to properly store data in that format (then you might consider XML serialization which is somewhat human readable). Be advised, it might be extremly confusing when you start working with serialization.

If you are not familiar with pointers and bit operations you should check them first , as they are basic for C/C++

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