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
21.9k25 gold badges107 silver badges178 bronze badges
asked May 19, 2020 at 22:32

1 Answer 1

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:

answered May 19, 2020 at 22:42
Sign up to request clarification or add additional context in comments.

2 Comments

To insure successfully reading the same value, especially large and small values, see Printf width specifier to maintain precision of floating-point value
Thanks so much Marco...I was struggling on that for quite a few hours.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.