Printf Variable String Length Specifier

Assuming that your string doesn't have any embedded NUL characters in it, you can use the %.*s specifier after casting the size_t to an int:

string_t *s = ...;
printf("The string is: %.*s\n", (int)s->len, s->data);

That's also assuming that your string length is less than INT_MAX. If you have a string longer than INT_MAX, then you have other problems (it will take quite a while to print out 2 billion characters, for one thing).


A simple solution would just be to use unformatted output:

fwrite(x.data, 1, x.len, stdout);
This is actually bad form, since `fwrite` may not write everything, so it should be used in a loop;
for (size_t i, remaining = x.len;
     remaining > 0 && (i = fwrite(x.data, 1, remaining, stdout)) > 0;
     remaining -= i) {
}

(Edit: fwrite does indeed write the entire requested range on success; looping is not needed.)

Be sure that x.len is no larger than SIZE_T_MAX.

Tags:

C

String