2

I have an float array, that has 189 elements (running from index 0 to index 188). I'm having trouble writing this array out to a file. Suppose the first element is 45.6, and the second element is 67.9, I want my output file to look like this:

0, 45.6
1, 67.9

and so on. I've tried the function shown below, and the result is my output file has odd characters in it.

void writeCorrelationToFile(float slidingCorrelator[])
{  
    FILE *fp;
    fp=fopen("CorrelationResult.txt","w");
    printf("inside writeCorrelationToFile, writing out array using fwrite  \n");
    fwrite(slidingCorrelator,4,sizeof(slidingCorrelator),fp);
    fclose(fp);
}

I get an output file like this:

�'���۽l^��(���!>

I have also tried setting sizeof(slidingCorrelator) to 189, but that also did not help.

codewario
  • 19,553
  • 20
  • 90
  • 159
Raj Nijjar
  • 23
  • 1
  • 3

1 Answers1

7

The fwrite() function writes binary data. What you want to write is the human readable (i.e. text) representation of your float values, not the binary representation.

You can do this using fprintf():

float slidingCorrelator[N];
FILE *fp;

// ... fill the array somehow ...

fp = fopen("CorrelationResult.txt", "w");
// check for error here

for (unsigned i = 0; i < N; i++) {
    fprintf(fp, "%d, %f\n", i, slidingCorrelator[i]);
    // check for error here too
}

fclose(fp);

Don't forget to check the return value of those functions to detect errors. For more information, see:

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • To insure successfully reading the same value, especially large and small values, see [Printf width specifier to maintain precision of floating-point value](https://stackoverflow.com/a/19897395/2410359) – chux - Reinstate Monica May 20 '20 at 02:19
  • Thanks so much Marco...I was struggling on that for quite a few hours. – Raj Nijjar May 20 '20 at 04:33