I have a struct that contains a string and a length:
typedef struct string {
char* data;
size_t len;
} string_t;
Which is all fine and dandy. But, I want to be able to output the contents of this struct using a printf
-like function. data
may not have a nul terminator (or have it in the wrong place), so I can't just use %s
. But the %.*s
specifier requires an int
, while I have a size_t
.
So the question now is, how can I output the string using printf
?
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);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With