MaMu
MaMu

Reputation: 1869

Appending x characters to string

I'd expect, that the lines below would take at most 6 chars from variable filename and append it to variable dmpfilename:

sprintf (dmpfilename, "InstrumentList_FULL.csv_%.*s",6,  filename);
sprintf (dmpfilename, "InstrumentList_FULL.csv_%*s" ,6,  filename);
sprintf (dmpfilename, "InstrumentList_FULL.csv_%6s",     filename);

But they append more characters (they take filename till '\0'). What am I doing wrong?

Upvotes: 0

Views: 38

Answers (1)

unwind
unwind

Reputation: 399793

Your first attempt should work, it uses the precision which has the correct semantics according to the manual page:

This gives [...] the maximum number of characters to be printed from a string for s and S conversions.

For the others, you're not doing anything wrong, except having the wrong expectations. The manual page clearly states:

In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

You're expecting truncation but not getting it, since that's not how it works.

I tested the precision-based one (with %.*s) and it worked fine.

Upvotes: 4

Related Questions