c - Easiest way to allocate "blank" block of data to .dat file -
looking quick way allocate block of data managed disk. i'm allocating block of 50 structs, , while of memory allocates fine, when read junk messages returned in of fields should blank. assume me allocating space incorrectly somehow allows junk memory leak in there.
if ((fpbin = fopen(binaryfile, "w+b")) == null) { printf("could not open binary file %s.\n", binaryfile); return; } fwrite(fpbin, sizeof(struct student), 50, fpbin); //write entire hash table disk
struct definition
typedef struct student { char firstname[20]; //name char lastname[20]; double amount; //amount owed char stuid[5]; //4 digit code }student;
is how taught, yet i'm still getting junk in data instead of being clean slate. question: how set fields blank?
answer:
student tempstu[50] = {0}; fwrite(tempstu, sizeof(struct student), bucketsize, fpbin); //write entire hash table disk
fwrite(fpbin, sizeof(struct student), 50, fpbin);
you're writing file pointer, not student structs, disk. first fpbin
should instead pointer data. data can array of 50 student structs initialized 0, perhaps calloc or defining @ file scope, has somewhere. instead, writing 50*sizeof(struct student) bytes fpbin
pointer, undefined behavior -- you'll either crash access violation or you'll write junk disk. junk you're getting when read back.
also, using constant 50
bad practice ... should variable (or manifest constant) holds number of students you're writing out.
btw, on linux , other posix systems, allocate block of zeroes on disk writing last byte (or in other way making file large).
Comments
Post a Comment