read byte by byte from a file

How can I read a file in form of bytes, not using a vector.

By using this, I can read the entire file into a vector of Bytes.

std::basic_ifstream<BYTE> file(driveName, std::ios::binary);
vector<BYTE> x = std::vector<BYTE>(
    (std::istreambuf_iterator<BYTE>(file)),
     std::istreambuf_iterator<BYTE>() );

But, I want to read 512 bytes first, then 'x' bytes, 'x1' bytes etc., The resize option doesnt work here.

I saw this link, reading the binary file into the vector of unsigned chars, which created more confusion.

Any help on this would be appreciated.

Upvotes: 0

Views: 8121

Answers (1)

Andriy Tylychko
Andriy Tylychko

Reputation: 16256

You can use lower-level interface:

std::ifstream ifs(filename, std::ios::binary);
char buf1[512];
ifs.read(buf1, sizeof(buf1) / sizeof(*buf1));
char buf2[x];
ifs.read(buf2, sizeof(buf2) / sizeof(*buf2));
char buf3[x1];
ifs.read(buf3, sizeof(buf3) / sizeof(*buf3));

Just check for EOF and errors.

Upvotes: 1

Related Questions