fwrite/fread for complex datatype numbers giving zero as result

332 views Asked by At

I've tried fwrite/fread for int, char and complex datatypes. They all worked well except complex. The read values of both the real and imaginary parts are all zero.

Code:

int main()
{
    typedef complex<float> cf;
    
    FILE *stream;
    stream = fopen("fread.out", "w+t");
    
    unsigned int n1 = 6;
    char *c1 = "this is a test";   
    cf cp1{2.0, 3.0};
    
    fwrite(&n1, sizeof(unsigned int), 1, stream);
    fwrite(c1, sizeof(char), strlen(c1), stream);
    fwrite(&cp1, sizeof(cf), 1, stream);
    fclose(stream);
    
    stream = fopen("fread.out", "r+t");
    unsigned int n2;
    char c2[20];
    cf cp2;
    
    fread(&n2, sizeof(unsigned int), 1, stream);
    fread(&c2, sizeof(char), strlen(c2), stream);
    fread(&cp2, sizeof(cf), 1, stream);
    
    fclose(stream);   
    return 0;
}

Output:

n2 = 6,c2 = this is a test, cp2 = 0.000000 + i*0.000000
1

There are 1 answers

0
Vasilij On BEST ANSWER

You've got a problem here:

 fread(&c2, sizeof(char), strlen(c2), stream);

strlen(c2) gives you garbage, because c2 is not initialized. You should change c2 to c1 in this strlen function to make this example work.

For production ready code one should choose a more complex serialization technique, probably one of the existing solutions.