Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read several bytes, jump over N bytes, and then read several bytes again. how?

Tags:

c++

I have a binary file, a.bin, which contains 768 bytes.

And I want put the bytes 16-256, 272-512, 528-768 into

char data[720]

I did somethin like

ifstream a1;
a1.open("a.bin", ios::in|ios::binary)

char tmp[256]
a1.read(tmp,256)

And then I did some loop and copy tmp to data[720] in logic. But that looks really stupid. So I want to ask

  1. How can I read data to certain position of a char arry ?

    a1.read(tmp[2],2) // not allowed, how to achieve this?

  2. How can I jump over certain day?

    a1.read(tmp16,16); I can use this to jump 16 bytes and neve use tmp16, but it looks ugly.

like image 778
thundium Avatar asked Sep 05 '13 15:09

thundium


1 Answers

I believe ignore is the way to go.

You go.

a1.ignore(16);                   // [1]
a1.read(data, 256-16);           // [2] 
a1.ignore(272-256);              // [3]
a1.read(&data[256-16], 512-272); // [4] 
// and so on
  1. ignore 1st 16 bytes
  2. you can go with data here, cause it is the address of the 1st byt of the buffer, essentially the same as &data[0]
  3. skip next unwanted bytes
  4. this will take and pass address of data[256-16+1] as the buffer to read into. Plain data[17] would just take a value from there, while & operator takes its address. I put 256-16 in there cause that is the number of bytes read in previous call, and we want to start reading at the next free space. Numbering from 0 this is it.
like image 77
luk32 Avatar answered Sep 28 '22 06:09

luk32