Little improvised
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
static size_t lendian_fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream)
{
int x = 1;
if ( *((char*)&x) == 1)
{
/* Little endian machine, use fwrite directly */
return fwrite(ptr, size, nmemb, stream);
}
else
{
if(size == sizeof(uint8_t)) //1 Byte
{
return fwrite(ptr, size, nmemb, stream);
}
else if(size == sizeof(uint16_t)) //2 Byte
{
/* Big endian machine, pre-process first */
unsigned char *buffer = malloc(size*nmemb);
unsigned char *input = (unsigned char*) ptr;
for (uint32_t i=0; i<nmemb; i++)
{
buffer[2*i] = input[2*i + 1];
buffer[2*i + 1] = input[2*i];
}
int ret =fwrite((void*)buffer, size, nmemb, stream);
free(buffer);
return ret;
}
else if(size == sizeof(uint32_t)) //4 Byte
{
/* Big endian machine, pre-process first */
unsigned char *buffer = malloc(size*nmemb);
unsigned char *input = (unsigned char*) ptr;
for (uint32_t i=0; i<nmemb; i++)
{
buffer[4*i ] = input[4*i + 3];
buffer[4*i + 1] = input[4*i + 2];
buffer[4*i + 2] = input[4*i + 1];
buffer[4*i + 3] = input[4*i ];
}
int ret =fwrite((void*)buffer, size, nmemb, stream);
free(buffer);
return ret;
}
else if(size == sizeof(uint64_t)) //8 Byte
{
/* Big endian machine, pre-process first */
unsigned char *buffer = malloc(size*nmemb);
unsigned char *input = (unsigned char*) ptr;
for (uint32_t i=0; i<nmemb; i++)
{
buffer[8*i ] = input[4*i + 7];
buffer[8*i + 1] = input[4*i + 6];
buffer[8*i + 2] = input[4*i + 5];
buffer[8*i + 3] = input[4*i + 4];
buffer[8*i + 4] = input[4*i + 3];
buffer[8*i + 5] = input[4*i + 2];
buffer[8*i + 6] = input[4*i + 1];
buffer[8*i + 7] = input[4*i ];
}
int ret =fwrite((void*)buffer, size, nmemb, stream);
free(buffer);
return ret;
}
else
{
printf("%s Function received invalid element size:%ld\n",__FUNCTION__,size);
return -1;
}
}
}
int main()
{
uint8_t buf1[8] = { 0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88 };
uint16_t buf2[4] = { 0x1122,0x3344,0x5566,0x7788 };
uint32_t buf3[2] = { 0x11223344, 0x55667788 };
uint64_t buf4 = { 0x1122334455667788 };
FILE *ofp = NULL;
if((ofp=fopen("file.bin","wb"))==NULL)
{
printf("Cannot open output file!");
return -1;
}
lendian_fwrite(&buf1, sizeof(uint8_t),sizeof(buf1),ofp);
lendian_fwrite(&buf2, sizeof(uint16_t),sizeof(buf2)/sizeof(uint16_t),ofp);
lendian_fwrite(&buf3, sizeof(uint32_t),sizeof(buf3)/sizeof(uint32_t),ofp);
lendian_fwrite(&buf4, sizeof(uint64_t),sizeof(buf4)/sizeof(uint64_t),ofp);
fclose(ofp);
}