Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf Variable String Length Specifier

Tags:

c

string

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?

like image 369
Jeremy Rodi Avatar asked Oct 02 '13 20:10

Jeremy Rodi


2 Answers

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).

like image 136
Adam Rosenfield Avatar answered Oct 04 '22 02:10

Adam Rosenfield


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.

like image 25
Kerrek SB Avatar answered Oct 04 '22 02:10

Kerrek SB