0

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*’.

Venkatesan
  • 422
  • 3
  • 6
  • 19
  • 1
    You might take a look here: http://stackoverflow.com/questions/2469531/reading-and-writing-c-vector-to-a-file?rq=1 – Joe Z Dec 09 '13 at 05:22

2 Answers2

1

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
woolstar
  • 5,063
  • 20
  • 31
1

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

Mine
  • 4,123
  • 1
  • 25
  • 46
  • 1
    Usual comments about byte-order dependence apply. (ie. If you write data from a little endian machine, you'll have to do extra work on a big endian machine when reading it, and vice versa.) – Joe Z Dec 09 '13 at 05:28
  • Yes, byte-order should be considered depending on the actual usage of the code. – Mine Dec 09 '13 at 05:31
  • I like `sizeof(v[0])` better than `sizeof(unsigned short)` because if someone foolishly changes the type of the vector, the first form will not require updating, thus following the DRY principle. – woolstar Dec 09 '13 at 05:47