Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fprintf printing a bunch of NULLs at the beginning

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Drop toString() function from source, it’s redundant.

  2. Use below statements instead in printRecordToFile()

    printf ("%d (%s, %f)", delete++, r->name, r->field1);
    fprintf (file, "(%s, %f)", r->name, r->field1);
  1. Use meaningful names for structure attributes/members.

  2. 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.

  3. Use Valgrind to trace memory error & leaks. It’s a pretty nifty tool for C programmers.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading