1

I'm trying to write a linked list into a binary file using this function

void agregar_cliente(string name, string alias, string telefono, string email) {
    if (principio == nullptr) {
        principio = new Client_node;
        principio->name = name;
        principio->alias = alias;
        principio->telefono = telefono;
        principio->email = email;
        principio->numero_de_ventas = 0;
        principio->siguiente = nullptr;
        actual = principio;
    }
    else {
        actual = principio;

        while (actual->siguiente != nullptr) {
            actual = actual->siguiente;
        }
        actual->siguiente = new Client_node;
        actual->siguiente->siguiente = nullptr;
        actual = actual->siguiente;
        actual->name = name;
        actual->alias = alias;
        actual->telefono = telefono;
        actual->email = email;
        actual->numero_de_ventas = 0;
    }
    ofstream escritura_clientes;
    escritura_clientes.open("clientes.bin",ios::out,ios::binary);
    if (escritura_clientes.is_open())
    {
        actual = principio;
        while (actual != nullptr) {
            escritura_clientes.write(reinterpret_cast<char*> (actual), sizeof(Client_node));
            actual = actual->siguiente;
        }

    }
    escritura_clientes.close();}

Problem is, that it will randomly save the email. Sometimes it does sometimes it doesn't, in both situations, I don't make any changes.

This is the list I'm using:

struct Client_node {
    string name;
    string alias;
    string telefono;
    string email;
    int numero_de_ventas;
    Client_node* siguiente;
};
Client_node* principio;
Client_node* actual;
Christian
  • 4,902
  • 4
  • 24
  • 42
  • 1
    You can't write `std::string` to a file like that. The string object only contains some pointers to the actual data. You need to serialize your struct. A common way is to write the length of the string followed by the string data for each member. Having a raw pointer in the struct is also going to cause issues. – Retired Ninja Sep 07 '22 at 01:31
  • You might be surprised to learn that `sizeof(Client_node)` is always the same value, a compile-time constant, whether its particular object's strings are empty, or whether each one contains an entire chapter from "War and Peace". This is not how objects work in C++. – Sam Varshavchik Sep 07 '22 at 01:36

0 Answers0