Link to home
Start Free TrialLog in
Avatar of rt2001
rt2001Flag for India

asked on

help - code with assembling pkt c++

Hello,

I would like to get some help with a problem, please.

I need to write a method that would assemble a buffer of say 14 bytes ( a packet) in which I need to assemble side by side a uint8 value1, a string value1_name, a uint8 value2,  and contents of a file whose pointer and size are given.

the buffer location must be compiler allocated. The parameters value1_name, file ptr, size and value1 are passed to the function.

What would be the best way to write this?

Thank you in advance.
Avatar of Infinity08
Infinity08
Flag of Belgium image

Is this for an assignment ? If so, please tell us, so we can help you in the best possible way.


>> What would be the best way to write this?

Write a function that takes the mentioned data as parameters, then simply allocate a buffer with enough memory (enough to contain all data), and copy the data into that buffer one by one using a pointer that "walks" through the buffer as it gets filled up.

Make use of memcpy and fread :

        http://www.cplusplus.com/reference/clibrary/cstring/memcpy.html
        http://www.cplusplus.com/reference/clibrary/cstdio/fread.html
Avatar of rt2001

ASKER

No this is not an assignment. I am a professional.
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rt2001

ASKER

Thank you infinity for your reply.

I am thinking of using malloc instead of creating an obj. and just passing the params to a asemble function.

I would like to discuss this question thread a little further and get some ideas from you. I want to make some improvements to my code in a day or 3. Can I keep this question open if you don't mind. (e.g. I would like to maybe create a generic assemble function to assemble packets with different components. Or add this packet struct as a part of a bigger class that everything is a part of. Don't know if it would make sense to have structs for sets of data that constitute pkts of different types.)
Thank you again.
Avatar of rt2001

ASKER

Should I be following this obj creating approach instead of a malloc
>> Can I keep this question open if you don't mind.

No problem.


>> (e.g. I would like to maybe create a generic assemble function to assemble packets with different components.

What you maybe need is virtual methods, one for each packet type. They could then be treated generically.


>> Should I be following this obj creating approach instead of a malloc

I'm not sure what approach you have in mind, but by using a struct (or class), you group data that logically belongs together, which makes the code more readable, and more modular.
Avatar of rt2001

ASKER

Thank you infinity, for your help, I think I am done.