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.
1 Answer 1
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: