0

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.

Community
  • 1
  • 1

1 Answers1

1

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.

Andriy Tylychko
  • 15,244
  • 5
  • 56
  • 103
  • 1
    I wanted to read BYTE by BYTE. This reads character by character. In some compilers where, sizeof(char) is greater than 1 Byte, will it work? – beginner to forensic analysis Oct 24 '13 at 08:23
  • size(char) is always 1. the only thing which is not guaranteed is that char has 8 bit it seems -> http://stackoverflow.com/questions/4266771/char-size-confusion. In the majority of cases however, 1byte should have 8 bits – codeling Oct 24 '13 at 08:32
  • 1
    @andy-t: but there's one more problem with your solution: it reads *characters* instead of *bytes*. And there *is* a difference: the type *char* is usually implemented as signed integer, so when you read byte, e.g. 0xFE, it will be interpreted as -2 instead of 254 in decimal. So, for example, this comparison will not work afterwards: `if (c == 0xFE) ...`. Therefore one needs to use `unsigned char` for them to work as bytes. – SasQ Jun 11 '15 at 03:35