how to write binary copy of structure array to file
Posted
by
cerr
on Stack Overflow
See other posts from Stack Overflow
or by cerr
Published on 2014-08-21T03:31:34Z
Indexed on
2014/08/21
4:20 UTC
Read the original article
Hit count: 193
I would like to write a binary image of a structure array to a binary file. I have tried this so far:
#include <stdio.h>
#include <string.h>
#define NUM 256
const char *fname="binary.bin";
typedef struct foo_s {
int intA;
int intB;
char string[20];
}foo_t;
void main (void)
{
foo_t bar[NUM];
bar[0].intA = 10;
bar[0].intB = 999;
strcpy(bar[0].string,"Hello World!");
Save(bar);
printf("%s written succesfully!\n",fname);
}
int Save(foo_t* pData)
{
FILE *pFile;
int ptr = 0;
int itr = 0;
pFile = fopen(fname, "w");
if (pFile == NULL) {
printf("couldn't open %s\n", fname);
return;
}
for (itr = 0; itr<NUM; itr++) {
for (ptr=0; ptr<sizeof(foo_t); ptr++)
{
fputc((unsigned char)*((&pData[itr])+ptr), pFile);
}
fclose(pFile);
}
}
but the compiler is saying aggregate value used where an integer was expected
fputc((unsigned char)*((&pData[itr])+ptr), pFile);
and I don't quite understand why, what am I doing wrong?
Thanks!
© Stack Overflow or respective owner