iostream - BYTE array

J

Joy Maitland

how to use <iostream> to read a file to a const BYTE array?

const BYTE *pbBinary
 
M

Maxim Yegorushkin

how to use <iostream> to read a file to a const BYTE array?

const BYTE *pbBinary

You don't normally read a file into a pointer. You read a file into an
array and point that pointer to that array:

#include <iostream>
#include <vector>
#include <iterator>

int main()
{
typedef unsigned char BYTE;
// read from std::cin
std::vector<BYTE> bytes(
(std::istreambuf_iterator<char>(std::cin))
, (std::istreambuf_iterator<char>())
);
if(bytes.empty())
; // no bytes have been read

BYTE const* pbBinary = &bytes[0];
}
 
J

Joy Maitland

why when i change the code from std::cin to read from file
c:/test2.xml I got error

=======================
typedef unsigned char BYTE;
std::eek:fstream file1("c:/test2.xml");

// read from std::cin
std::vector<BYTE> bytes(
(std::istreambuf_iterator<char>(file1))
, (std::istreambuf_iterator<char>())
);
if(bytes.empty())
; // no bytes have been read

BYTE const* pbBinary = &bytes[0];

===========================

1>d:\snd\remote\remotedemo\app\virtualawear\main.cpp(31) : error
C2440: '<function-style-cast>' : cannot convert from 'std::eek:fstream'
to 'std::istreambuf_iterator<_Elem,_Traits>'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> No constructor could take the source type, or constructor
overload resolution was ambiguous

============================






how to use <iostream> to read a file to a const BYTE array?

const BYTE *pbBinary

You don't normally read a file into a pointer. You read a file into an
array and point that pointer to that array:

#include <iostream>
#include <vector>
#include <iterator>

int main()
{
typedef unsigned char BYTE;
// read from std::cin
std::vector<BYTE> bytes(
(std::istreambuf_iterator<char>(std::cin))
, (std::istreambuf_iterator<char>())
);
if(bytes.empty())
; // no bytes have been read

BYTE const* pbBinary = &bytes[0];
}
 
M

Maxim Yegorushkin

why when i change the code from std::cin to read from file
c:/test2.xml  I got error

=======================
typedef unsigned char BYTE;
                std::eek:fstream file1("c:/test2.xml");

Becuase you are using an output stream, rather than an input. Change
ofstream to ifstream.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top