Search code examples
cfwrite

fwrite printing garbage values like @@@@@


double *array_out;
.......
FILE * pFile;
pFile = fopen ("Q1_n_iter.bin", "wb");
fwrite(array_out,sizeof(double),n*n,pFile);
fclose (pFile);

I have checked array_out is correctly populated, I am not able to figure out why it prints garbage instead of values in it.


Solution

  • The values fwrite writes into a file is not to be read directly with human eyes. You should let computer interpret them for you with fread or something. For example, you could do the following:

    #include <stdio.h>
    #include <stdlib.h>
    
    char * filename = "Q1_n_iter.bin";
    
    int main( ) {
        double * array_out;
        double * array_in;
        FILE * pFile;
    
        array_out = malloc( 3 * sizeof * array_out );
    
        array_out[0] = 0.12;
        array_out[1] = 1.35;
        array_out[2] = 2.80;
    
        pFile = fopen( filename, "wb" );
        fwrite( array_out, sizeof * array_out, 3, pFile );
        fclose( pFile );
        free( array_out );
    
        array_in = malloc( 3 * sizeof * array_in );
        pFile = fopen( filename, "rb" );
        fread( array_in, sizeof * array_in, 3, pFile );
    
        for ( int i = 0; i < 3; i++ )
            printf( "%d: %.2f\n", i, array_in[i] );
    
        free( array_in );
    
        return 0;
    }
    

    And would receive the following output:

    0: 0.12
    1: 1.35
    2: 2.80
    

    If you want to print formatted data into the file, for a human to read, then you should rather use the function fprintf. It works just like the printf, with an additional field for specifying the output stream.

    fprintf( FILE * stream, const char * FormatString, ... );
    

    In your case, you should do it in the following manner:

    // ...
    
    for ( int i = 0; i < n * n; i++ )
        fprintf( pFile, "%.2f ", array_out[i] );
    
    // ...
    

    Remove ".2" if you do not want rather 6 digits after the decimal point as default, specify another number if you want any other precision.

    Edit:

    To create the file with the filename determined with command-line arguments, you could do the following:

    #include <stdio.h>
    #include <stdlib.h>
    
    char * filename;
    
    int main( int argc, char * argv[] ) {
    
        // declarations
        // and what not
    
        filename = malloc( 256 );
        sprintf( filename, "Q1_%d_%d.bin", n, iter );
    
        // whatever
        free( filename );
    
        return 0;
    }
    

    Or, if you don't want to use the sprintf, include the string.h library and:

        // ...
        strcpy( filename, "Q1_" );
        strcat( filename, argv[1] );
        strcat( filename, "_" );
        strcat( filename, argv[2] );
        strcat( filename, ".bin" );
        // ...