I am trying to allocate a single block of shorts, fwrite it to a file, and then read it back. But the data that gets written into the file doesn't match what is coming out. I've isolated the problem to the following bit of code. Any ideas what I'm doing wrong?
#define CHUNK_SIZE 1000
void xwriteStructuresToFile(FILE *file, void * structureData)
{
assert((fwrite(structureData, sizeof(short), CHUNK_SIZE, file)) == CHUNK_SIZE);
}
void wwbuildPtxFiles(void)
{
FILE *file = fopen("s:\\tv\\run32\\junky.bin", WRITE_BINARY);
int count = 10;
short *ptx = (short *) calloc(CHUNK_SIZE * count, sizeof(short ) );
memset(ptx, '3', sizeof(short) * CHUNK_SIZE * count);
for (int dayIndex = 0; dayIndex < count; ++dayIndex)
xwriteStructuresToFile(file, (void *) &ptx[ CHUNK_SIZE * sizeof(short) * dayIndex ]);
free(ptx);
fclose(file);
file = fopen("s:\\tv\\run32\\junky.bin", READ_BINARY);
int xcount = CHUNK_SIZE * count * sizeof(short );
for (int i = 0; i < xcount; ++i)
{
char x;
if ((x = getc(file)) != '3')
assert(false);
}
}
A few things:
the way you open the file, I am not sure about your constants but they should read
"wb"
to write a binary file and "rb"
to read.
Never put a statement in an assert, an assert is removed when the program is compiled in release mode. Instead, check return value and assert on that
e.g.
bool ok =fwrite(structureData, sizeof(short), CHUNK_SIZE, file)) == CHUNK_SIZE;
assert(ok);
although you should not assert on this, instead you should print out a proper error message. assert are for programming errors, not runtime errors.
short *ptx = (short *) calloc(CHUNK_SIZE * count, sizeof(short ) );
the above line contains a number of issues:
never cast return value of calloc
in C. short *ptx = calloc...
should suffice,
if you get a warning, #include <stdlib.h>
you should use the form calloc( count, CHUNK_SIZE * sizeof( short ));
it otherwise looks a bit unclear.
( calloc takes number,size as arguments)
for (int dayIndex = 0; dayIndex < count; ++dayIndex)
xwriteStructuresToFile(file,
(void *) &ptx[ CHUNK_SIZE * sizeof(short) * dayIndex ]);
not sure what you are doing there, replace the two statements with
fwrite( ptx, CHUNK_SIZE * sizeof( short ), count, fp );
that should write the whole array.