Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this statement mean ? printf("[%.*s] ", (int) lengths[i],

Tags:

c

I was reading this page http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html there is one line

printf("[%.*s] ", (int) lengths[i],
              row[i] ? row[i] : "NULL");

from code

    MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;

num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
{
   unsigned long *lengths;
   lengths = mysql_fetch_lengths(result);
   for(i = 0; i < num_fields; i++)
   {
       printf("[%.*s] ", (int) lengths[i],
              row[i] ? row[i] : "NULL");
   }
   printf("\n");

}

what does [%.*s] mean in that code ?

like image 501
Vivek Goel Avatar asked Feb 24 '23 19:02

Vivek Goel


2 Answers

[%.*s] is a printf format string meaning:

  • the first argument should be an integer (specifying maximum length of a string to print).
  • the second argument should be the string itself.
  • the [ and ] (and trailing space) are transferred as-is.

Normally, you would see something like .7s which means a 7-character string. The use of * for the length means to take it from the argument given.

So what that entire line does is to print a string , the length of which is found in lengths[i], and the value of which is row[i] (unless row[i] is NULL, in which case it uses the literal string "NULL").

like image 141
paxdiablo Avatar answered Mar 08 '23 07:03

paxdiablo


%.*s is an output format string.

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

printf("[%.*s] ", (int) lengths[i], row[i] ? row[i] : "NULL"); 

Specifically in this case it means to print the the second argument (contents of row[i] or 'NULL' if contents of row[i] evaluate to false) with a maximum of lengths[i] characters. The square brackets are not part of the formatting, they get printed themselves

like image 27
jon_darkstar Avatar answered Mar 08 '23 06:03

jon_darkstar