JamesGold
JamesGold

Reputation: 815

Vector data written to binary file isn't the same when read back into another vector, why?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "ReadText.h"
using namespace std;

const string FILE_NAME = "TopicIinBasic.txt";

template<typename T>
char * as_bytes( T &inType );


int main()
{
    vector<int> vec(2, 2);

    vector<int> receive(2);

    fstream write( "myFile.dat", ios::out | ios::binary );

    write.write( as_bytes(vec[0]), sizeof(vec[0] * 2) );

    write.close();

    fstream read( "myFile.dat", ios::in | ios::binary );

    read.read( as_bytes(receive[0]), sizeof(vec[0] * 2) );

    cout << receive[0] << ' ' << receive[1] << endl;    

    return 0;
}

template<typename T>
char * as_bytes( T &inType )
{
    void* addr = &inType;

    return static_cast<char*>(addr);
}

I first write the contents of vec to the binary file. Then close the file. Then open it again in read mode. Then I try to put the contents of the binary file into receive. But when I display receive's contents, the output is 2 0, not 2 2. Why is this happening?

Thanks.

Upvotes: 1

Views: 283

Answers (1)

user149341
user149341

Reputation:

You are taking the size of the expression vec[0] * 2, which is the same size as vec[0]. As a result, you're only writing one element!

Moving the * 2 outside the parentheses will fix it. (I've also moved it up front for clarity.)

write.write( as_bytes(vec[0]), 2 * sizeof(vec[0]) );

Upvotes: 3

Related Questions