Home > other >  In C storing and retrieving of character vector (vector<char>) of all zero value (i.e. '
In C storing and retrieving of character vector (vector<char>) of all zero value (i.e. '

Time:01-11

Using fstream I have created a file to store a fixed length sequence of zero value (0) i.e. '\0' ASCII code available in a character vector (vector).

fstream Fpt;

Fpt.open("Data.bin",ios::out|ios::binary);

std::vector<char> V;

char c=0;

for(int i=0;i<10;i  )V.push_back(c);

Fpt.write((char *)&V,10);

Fpt.close();

Fpt.open("Data.bin",ios::in | ios::out|ios::binary);

V.clear();

Fpt.read((char *)&V, 10);

for(auto v: V) printf("(%c,%d,%X)",v,v,v);

But the output is looking like (▌,-35,FFFFFFDD) (▌,-35,FFFFFFDD) ...

CodePudding user response:

You write the vector object itself, not the data wrapped by the vector (which is located on the heap).

You need to get a pointer to the data itself and write that:

Fpt.write(V.data(), V.size());

Similarly when you read the data, you need to read it into the wrapped data:

V = std::vector<char>(10);  // Reset the vector, remembering to set its size
Fpt.read(V.data(), V.size());

CodePudding user response:

This statement is not correct:

Fpt.write((char *)&V,10);

You are getting the address of the vector object V which is stored on the stack. What you want is the address of the underlying buffer (stored on the heap) that V points at and so you need to use the data member function.

So instead do this:

Fpt.write( V.data(), 10 );

Or this:

Fpt.write( &V[0], 10 );

Important Note

What you do here is a bad idea:

char c=0;

for ( int i = 0; i < 10; i   ) V.push_back(c);

This will cause the vector to repeatedly reallocate its buffer once the size reaches capacity. This is bad in terms of performance.
Instead, write it like:

std::vector<char> V(10);

Now V will be initialized with 10 \0 characters. No need to use a loop to fill the container.

  •  Tags:  
  • Related