typedef struct record
{
float field1;
char *name;
} record;
void printRecordsTo(record **s, char *fileName, int size)
{
initializePrinter(fileName);
int i = 0;
while (i < size)
{
printRecordToFile(s[i]);
i++;
}
closePrinter();
}
static int delete = 0; // TODO: Remove
void printRecordToFile(record *r)
{
if (!file)
{
puts("Printer not initialized");
exit(1);
}
printf("%d %s", delete ++, toString(r)); // prints all correctly to stdout
fprintf(file, "%s", toString(r)); // includes many NULLs
}
char *toString(record *s)
{
float field1 = s->field1;
int len = 4;
char *field1Str = malloc(len + 1);
snprintf(field1Str, len + 1, "%f", field1);
char *name = s->name;
char *buf = malloc((1024) * sizeof(char));
snprintf(buf, 1023, "%s%s%s%s%s\n", "(", name, ", ", field1Str, ")");
return buf;
}
I can’t figure out why many NULLs are being printed by the fprintf for large files (of size ~1000 records). The function works fine for the small files (of size ~20 records) I used. I tested it against normal printf which prints the string representations of records correctly.
>Solution :
-
Drop
toString()function from source, it’s redundant. -
Use below statements instead in
printRecordToFile()
printf ("%d (%s, %f)", delete++, r->name, r->field1);
fprintf (file, "(%s, %f)", r->name, r->field1);
-
Use meaningful names for structure attributes/members.
-
If you’re still seeing garbage values, then perhaps you need to sit with a debugger to find out where structure data is being corrupted. With the info at hand we can only guess.
-
Use Valgrind to trace memory error & leaks. It’s a pretty nifty tool for C programmers.