AvengedFenix
AvengedFenix

Reputation: 13

Writing and reading a binary file to fill a vector - C++

I'm working on a project that involves binary files. So I started researching about binary files but I'm still confused about how to write and fill a vector from that binary file that I wrote before

Here's code: for writing.

void binario(){
ofstream fout("./Binario/Data.AFe", ios::out | ios::binary);
vector<int> enteros;
enteros.push_back(1);
enteros.push_back(2);
enteros.push_back(3);
enteros.push_back(4);
enteros.push_back(5);
//fout.open()
//if (fout.is_open()) {
    std::cout << "Entre al if" << '\n';
    //while (!fout.eof()) {
        std::cout << "Entre al while" << '\n';
        std::cout << "Enteros size: "<< enteros.size() << '\n';
        int size1 = enteros.size();
        for (int i = 0; i < enteros.size(); i++) {
            std::cout << "for " << i << '\n';
            fout.write((char*)&size1, 4);
            fout.write((char*)&enteros[i], size1 * sizeof(enteros));
            //cout<< fout.get(entero[i])<<endl;
        }
        //fout.close();
    //}
    fout.close();
    cout<<"copiado con exito"<<endl;
//} 
}

Here's code for reading:

oid leerBinario(){
vector<int> list2;

ifstream is("./Binario/Data.AFe", ios::binary);
    int size2;
    is.read((char*)&size2, 4);
    list2.resize(size2);


    is.read((char*)&list2[0], size2 * sizeof(list2));

    std::cout << "Size del vector: " << list2.size() <<endl;
    for (int i = 0; i < list2.size(); i++) {
        std::cout << i << ". " << list2[i] << '\n';
    }
    std::cout << "Antes de cerrar" << '\n';
    is.close();
}

I don't know if I'm writing correctly to the file, this is just a test so I don't mess up my main file, instead of writing numbers I need to save Objects that are stored in a vector and load them everytime the user runs the program.

Upvotes: 1

Views: 2216

Answers (1)

paddy
paddy

Reputation: 63481

Nope, you're a bit confused. You're writing the size in every iteration, and then you're doing something completely undefined when you try to write the value. You can actually do this without the loop, when you are using a vector.

fout.write(&size1, sizeof(size1));
fout.write(enteros.data(), size1 * sizeof(int));

And reading in:

is.read(&list2[0], size2 * sizeof(int));

To be more portable you might want to use data types that won't change (for example when you switch from 32-bit compilation to 64-bit). In that case, use stuff from <cctype> -- e.g. int32_t for both the size and value data.

Upvotes: 1

Related Questions