Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understand fprintf syntax

Tags:

c

printf

I know very little about C, but am trying to understand a programme written in it.

I've come across this line, but am unsure what it means:

fprintf(kinsh.fp, "%-.*lg", ndigits, kins[i+j*n]);

I think this means "Print a number with ndigits decimal places or significant figures (whichever is shorter) to kinsh (which is a file). However, I don't know what kins, which is an array, is doing in there.

Have I misunderstood - in context, it would make more sense if the line is reading from kinsh and writing into kins?

like image 204
Joni Avatar asked Dec 24 '22 23:12

Joni


1 Answers

The fprintf function is defined as follows :

int fprintf ( FILE * stream, const char * format, ... );

So, kinsh.fp is the FILE pointer. Now the format string "%-.*lg" is a C format string which implies this :

  1. The - implies left alignment
  2. Anything after the . implies the precision.
  3. The * implies that the precision is not hardcoded but provided as a parameter which is the first parameter after the format string i.e. ndigits.
  4. The lg will be treated by C99 compiler as double, Lg is for long double. (As mentioned by @mafso in comments, lg is Undefined Behaviour in C89)
  5. The actual data is in kins[i+j*n].

Edit

What is does : The statement writes a long double value stored at kins[i+j*n], with ndigits precision and left alignment, in the file pointed by kinsh.fp.

The general format string format is : %[parameter][flags][width][.precision][length]type

like image 87
a_pradhan Avatar answered Dec 28 '22 07:12

a_pradhan