1

I want to make a small change in one C code,in order to double-check some results.Just few relevant lines

 FILE           *f1_out, *f2_out;

/* open files */
if ((f1_out = fopen(vfname, "w")) == (FILE *) NULL)
{
   fprintf(stderr, "%s: Can't open file %s.\n", progname, vfname);
   return (-1);
}

Then goes some calculations and

yes = fwrite(vel, nxyz*sizeof(float), 1, f1_out);

How to change the last line to get the ascii output?

2
  • 7
    Why don't you simply replace it with fprintf()? Commented Apr 28, 2016 at 12:01
  • 3
    Note that if you open file for writing in binary mode, mode argument should be "wb". Also, casting NULL with (FILE *) is unnecessary. Commented Apr 28, 2016 at 12:05

3 Answers 3

2

Assuming that your vel is an array of floats, and your nxyz is the number of floats in that array, and that you want the output on the standard output and not on the file you opened:

for (int i = 0; i < nxyz; ++i) {
    printf("vel[%d] = %f\n", i, vel[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of yes = fwrite(vel, nxyz*sizeof(float), 1, f1_out);, use

for(i = 0; i < nxyz; ++i) {
  yes &= (fprintf(f1_out, "%d:\t%f\n", i, vel[i]) > 0);
}

2 Comments

Bitwise AND with the bits from the number of characters written seems like a strange thing to do.
@ThomasPadron-McCarthy It is fprintf(..) > 0. fprintf return negative value on failure. And for float, it must return > 0 if succesful.
1

To see all meaningful digits in a float as text use printf("%*e", some_precision, some_float)

#include <float.h>
fprintf(f1_out, "%.*e\n", FLT_DECIMAL_DIG - 1, *vel);

Comments

Your Answer

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.