File block

OK so i have to make this program that stores some values in blocks of 512 bytes

and i have a struct (example):
1
2
3
4
5
struct one{
unsigned short x;
unsigned short y [100];
char z;
};


i know im going to have to adds some padding of ~309

with blank char values
char padding [309];

my question is how can i write the struct in to the file with out converting the shorts to char array :( which would changes the size of the bytes

(i feel stupid for asking this)
Last edited on
As you asking how to write the unsigned shorts as binary?

BTW, there is no guarantee on the size of that structure. If take it that an unsigned short is 16 bytes, the structure isn't necessarily 16 + 16*100 + 1 bytes long. The compiler will apply alignment to the fields to improve access efficiency. You have to tell the compiler that your struct is byte aligned.
unsigned shorts are 2 bytes :P 16bits
http://en.wikipedia.org/wiki/Short_integer

im creating a system volume descriptor for unix (not exactly related) so i must make it 512 bytes :P


so i have to write it in binary? mmmmm
Yes, I meant 2 bytes/16 bits, sorry.

I was asking if you wanted to write it as binary, not suggesting it. But if you are doing volume stuff, then yes, I'd expect it to be written as binary.

You need to pack the struct, you have no choice.
what do you mean pack the struck?

i was just working on this:
1
2
3
4
     file.write( reinterpret_cast <const char*> (&superblock), sizeof(block1) );
     struct block1 blocky;
     file.read (reinterpret_cast <char*> (&blocky), sizeof(block1) );
     cout << blocky.flock;

**didnt work so far throws an error and by error i mean it prints a weird char and just wrong values

oh and where does the +1 come from in:

16 + 16*100 + 1 bytes long.
Last edited on
thanks for the help kbw! ^ ^
Topic archived. No new replies allowed.