简体   繁体   English

编写和读取二进制文件以填充矢量-C ++

[英]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. 我不知道我是否正确地写入文件,这只是一个测试,所以我不会弄乱我的主文件,而不是写数字,我需要保存存储在向量中的对象并每次加载它们用户运行该程序。

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). 为了更便于移植,您可能希望使用不会更改的数据类型(例如,当您从32位编译切换到64位时)。 In that case, use stuff from <cctype> -- eg int32_t for both the size and value data. 在这种情况下,请使用<cctype> -例如int32_t作为大小和值数据。

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

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