IMO, the best way to do this would be to store the lengths in whatever variable you see fit inside your program. I guess a straight forward integer would be good enough. Then, when it comes to writing this information to the file, call a wrapper function that will take care of formatting it correctly to become 1, 2 or 4 bytes in length. A similar wrapper function can be called to read this back in.
As for bit shifting, if you have them available, lookup the htonl() type functions, that convert CPU ordered bytes to a common external format, and back again. This will help you with the endian issues.
Some advice: don't hard code the lengths in the middle of function calls, like this:
>fwrite (&number, 2, 1, fp);
This will get you into trouble later. This may be going off track a bit for you, but here's an example of how you might control this type of thing:
Code:
#include <stdio.h>
typedef enum {LT_1, LT_2, LT_4, LT_COUNT } LengthType_t;
const int LengthTypeLengths[LT_COUNT] = { 1, 2, 4 };
int main(void)
{
int i;
LengthType_t myLT = LT_4;
for (i = 0; i < LT_COUNT; i++)
{
printf ("LT_%d has a length of %d\n",
i+1, LengthTypeLengths[i]);
}
printf ("The length of an LT_2 is %d\n",
LengthTypeLengths[LT_2]);
printf ("The length of myLT is %d\n",
LengthTypeLengths[myLT]);
return 0;
}
/*
Output:
LT_1 has a length of 1
LT_2 has a length of 2
LT_3 has a length of 4
The length of an LT_2 is 2
The length of myLT is 4
*/
This type of code would set you up for writing a wrapper function that could be invoked like so:
Code:
WriteData (MyData, strlen(MyData), LT_1, fp);
You could use #define's to achieve a similar result, but they rather limit what you can do in the future (thinking ahead here!).