unsigned char vector contents write to file

Aug 2, 2012 at 11:59am
how do i write the contents of an unsigned char vector to a file.
i get some output but its not the contents of the file.

1
2
3
4
5
6
7
8
vector<unsigned char> bufferType;

ofstream textout (pathname.c_str(), ios::out | ios::binary);
{
 textout.write((const char*)&bufferType[0], bufferType.size());
}

textout.close();


please help thx.
Aug 2, 2012 at 12:16pm
Works fine.

#include <vector>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
vector<unsigned char> bufferType;

bufferType.push_back('e');
bufferType.push_back('P');
bufferType.push_back('R');
bufferType.push_back('f');

string pathname("output.bin");

ofstream textout(pathname.c_str(), ios::out | ios::binary);
textout.write((const char*)&bufferType[0], bufferType.size());

textout.close();
}


The file generated contains the following in hex:
50656652



which is clearly the ASCII values of
ePRf ( e = 0x65, P = 0x50, R = 0x52, f=0x66)

If I open the file as a text file, the contents are clear in text:
ePRf



Aug 2, 2012 at 1:42pm
some other function was overwriting the contents of my vector and it was giving me bad results

thanks for your help.
Last edited on Aug 2, 2012 at 2:17pm
Topic archived. No new replies allowed.