Code:
//---------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define One 1
#pragma hdrstop
//---------------------------------------------------------------------------
/* Read some data from a binary file into an array. */
void FillArrayFromBinaryFile(const char *filename, int **ptrArray, int *ArraySz)
{
if(!filename)
{
fprintf(stderr, "NULL input filename.\n");
return;
}
else
{
FILE *filePtr = NULL;
if((filePtr = fopen(filename, "rb")) == NULL)
{
fprintf(stderr, "Error Opening:\"%s\" file.", filename);
return;
}
else
{
unsigned int Index = 0;
int *nArray = calloc(One, sizeof(int));
if(!nArray)
{
fprintf(stderr, "Memory Error.\n");
fclose(filePtr);
return;
}
for(;;)
{
if(1 != fread(&nArray[Index], sizeof(int), 1, filePtr))
break;
/* Each time. */
Index++;
nArray = realloc(nArray, Index+1 * sizeof(int));
fseek(filePtr, Index * (sizeof(int)+sizeof(char)), SEEK_SET);
}
*ptrArray = nArray;
*ArraySz = Index;
fclose(filePtr);
return;
}
}
}
void PrintArray(int *nArray, int Sz)
{
static int Index = 0;
for(Index = 0; Index < Sz; Index++)
printf("%d ", nArray[Index]);
printf("\n");
}
void WriteArrayToBinaryFile(const char *filename, int *nArray, int nSz)
{
if(!filename)
return;
else
{
FILE *filePtr = NULL;
if((filePtr = fopen(filename, "wb")) == NULL)
{
fprintf(stderr, "Error Opening:\"%s\" file.", filename);
return;
}
{
int Index = 0;
char cChar = ' ';
for(Index = 0; Index < nSz; Index++)
{
fwrite(&nArray[Index], sizeof(int), 1, filePtr);
fwrite(&cChar, sizeof(char), 1, filePtr);
}
fclose(filePtr);
return;
}
}
}
#pragma argsused
int main(int argc, char* argv[])
{
int nArraySz = 0;
int nArray[4];
int *ptrToArray = NULL;
nArray[0] = 1;
nArray[1] = 4;
nArray[2] = 6;
nArray[3] = 12;
WriteArrayToBinaryFile("Array.dat", nArray, 4);
memset(nArray,0, sizeof(nArray));
FillArrayFromBinaryFile("Array.dat", &ptrToArray, &nArraySz);
PrintArray(ptrToArray, nArraySz);
free(ptrToArray); ptrToArray = NULL;
printf("Hit enter to continue...\n");
getchar();
return 0;
}
//---------------------------------------------------------------------------
The above code will not solve your problem, but will give you a point to start. It writes an array to a binary file, then sets the array elements to zero and try to read them back again from the binary file. The difference is that using realloc i dont care what is the sizeof the array(number 8) in the binary file.
I just write to the file:
1 4 6 12
and try to get them back again.
*Possible bugs included. *
Bokarinho.