SKmay
SKmay

Reputation: 39

format string used in printf function in C programming

In this code:

sprint(buf_ptr, "%.*s", MAX_BUF_LEN, desc);

what does "%.*s", mean? what does "%20.20s" and "%.28s" mean- in snprintf?

Upvotes: 0

Views: 1519

Answers (2)

chux
chux

Reputation: 154218

what does "%.*s", mean?

desc, below, is a character pointer that need not point to a string1. Printing will continue until MAX_BUF_LEN charters (the precision) are printed or until a null character is read - which ever comes first.

sprint(buf_ptr, "%.*s", MAX_BUF_LEN, desc);

what does "%20.20s" ... mean- in snprintf?

Let us use two different values for clarity: "%19.21s".

desc is a character pointer that need not be a string. Printing will continue until 21 charters are printed or until a null character is read - which ever comes first. If the the number of charters to print is less than 19 (the minimum width), pad on the left with spaces to make at least 19 characters total.

sprint(buf_ptr, "%19.21s", desc);

what does ... "%.28s" mean- in snprintf?

Just like sprint(buf_ptr, "%.*s", 28, desc);


Loosely speaking, think of "%minimum.maximum s"


1 A string is a contiguous sequence of characters terminated by and including the first null character.

Upvotes: 1

Adrian Mole
Adrian Mole

Reputation: 51894

In the %*s format specification, the s indicates that the argument will be a (null-terminated) character string and the * (width specifier) says that the field width is given as the argument immediately preceding the string.

In your other examples, the width specifier(s) is(are) given as fixed values.

Actually, in the printf formats you give, there are both width and precision specifiers: the width is the value before the period and the precision is after. For strings, the width is the minimum output field size (space padded if necessary) and the precision is the maximum number of characters to print (string will be truncated, if necessary). In either case, if a * is specified for either, it will be assumed to be in the list of arguments (as an integer) immediately before the string it applies to.

Upvotes: 2

Related Questions