Using printf with a non-null terminated string

Suppose you have a string which is NOT null terminated and you know its exact size, so how can you print that string with printf in C? I recall such a method but I can not find out now...


Solution 1:

There is a possibility with printf, it goes like this:

printf("%.*s", stringLength, pointerToString);

No need to copy anything, no need to modify the original string or buffer.

Solution 2:

Here is an explanation of how %.*s works, and where it's specified.

The conversion specifications in a printf template string have the general form:

% [ param-no $] flags width [ . precision ] type conversion

or

% [ param-no $] flags width . * [ param-no $] type conversion

The second form is for getting the precision from the argument list:

You can also specify a precision of ‘*’. This means that the next argument in the argument list (before the actual value to be printed) is used as the precision. The value must be an int, and is ignored if it is negative.

— Output conversion syntax in the glibc manual

For %s string formatting, precision has a special meaning:

A precision can be specified to indicate the maximum number of characters to write; otherwise characters in the string up to but not including the terminating null character are written to the output stream.

— Other output conversions in the glibc manual

Other useful variants:

  • "%*.*s", maxlen, maxlen, val will right-justify, inserting spaces before;
  • "%-*.*s", maxlen, maxlen, val will left-justify.