CppMonster
CppMonster

Reputation: 1296

C++ Writing to file vector of byte

I have:

typedef unsigned char;
std::vector<byte> data;

I tried to save data in file this way (but I have error):

fstream file(filename,ios::out);
file.write(&data, data.size());

How to process or cast data to write it in file.

Upvotes: 6

Views: 15368

Answers (6)

Phil-ZXX
Phil-ZXX

Reputation: 3275

A lot of these solutions are only partially complete (lacking includes & casts), so let me post a full working example:

#include <vector>
#include <fstream>

int main()
{
    std::vector<std::byte> dataVector(10, std::byte{ 'Z' });

    const std::string filename = "C:\\test_file.txt";

    std::ofstream outfile(filename, std::ios::out | std::ios::binary);
    outfile.write(reinterpret_cast<const char*>(dataVector.data()), dataVector.size());

    return 0;
}

Upvotes: 4

geoyar
geoyar

Reputation: 31

I think that ostream.write (myVector[0], ...) will not work, as it does not work in reading into vector (that I had.) What works is ostream.write(MyVector.data(), ...) Note: for reading use ifstream.read(const_cast(MyVector.data()), ...)

Upvotes: 0

CppMonster
CppMonster

Reputation: 1296

*Statement file.write(&buffer[0],buffer.size()) makes error:

error C2664: 'std::basic_ostream<_Elem,_Traits>::write' : cannot convert parameter 1 from 'unsigned char *' to 'const char *'

*In my compiler (VS2008) I don't have data() method for vector.

I think below is correct:

file.write((const char*)&buffer[0],buffer.size());

Upvotes: 5

user2591612
user2591612

Reputation:

To store a vector in a file, you have to write the contents of the vector, not the vector itself. You can access the raw data with &vector[0], address of the first element (given it contains at least one element).

ofstream outfile(filename, ios::out | ios::binary); 
outfile.write(&data[0], data.size());

This should be fairly efficient at writing. fstream is generic, use ofstream if you are going to write.

Upvotes: 9

PaulMcKenzie
PaulMcKenzie

Reputation: 35455

You are to pass the address of the first element, not the address of the vector object itself.

     &data[0]

Note: Make sure that the vector is not empty before doing this.

Upvotes: 2

Sean
Sean

Reputation: 62532

Use vector::data to get a pointer the the underlying data:

file.write(data.data(), data.size());

Upvotes: 3

Related Questions