Venkatesan
Venkatesan

Reputation: 442

how to write a vector to a file in binary mode using c++?

so far i tried this,

#include<iostream>
#include<fstream>
#include <stdlib.h> 
#include<vector>
using namespace std;
int main()
{
   unsigned short array[3]={0x20ac,0x20ac,0x20ac};
   vector<unsigned short> v;
   std::ofstream file;
   file.open("1.txt", std::ios_base::binary);
   file.write((char*)(array), sizeof(array));
   v.push_back(array[0]);
   v.push_back(array[1]);
   v.push_back(array[2]);
   file.write((char *)v,sizeof(v));
   file.close();
}

i get a error message stan.cpp: In function ‘int main()’: stan.cpp:21:23: error: invalid cast from type ‘std::vector’ to type ‘char*’.

Upvotes: 0

Views: 1196

Answers (2)

woolstar
woolstar

Reputation: 5083

You have to find the pointer to the first element, then calculate the number of bytes by the number of elements in v * sizeof an element:

file.write((char*)(&v[0]), v.size() * sizeof(v[0])) ;

output:

% od -x 1.txt
0000000 20ac 20ac 20ac

Upvotes: 1

Mine
Mine

Reputation: 4241

You should either write each element one-by-one, or write the whole data by write(v.data(), v.size() * sizeof(unsigned short))

Upvotes: 1

Related Questions