13

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.

1
  • have a look at seekg Commented Sep 5, 2013 at 15:18

4 Answers 4

11

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.
Sign up to request clarification or add additional context in comments.

Comments

8

For the first question:

a1.read(&tmp[2], 2);

reads two bytes into tmp[2] and tmp[3].

For the second question:

a1.ignore(10);

skips 10 bytes.

Comments

1

To read to a certain point in an array you need to give it the address

a1.read(tmp+2, 2)

Or you can do

a1.read(&tmp[2], 2) // the & operator is the address of operator

Comments

1

To set the position to read in a stream use seekg.

http://en.cppreference.com/w/cpp/io/basic_istream/seekg

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.