Printf Variable String Length Specifier

I have a structure containing a string and a length:

typedef struct string { char* data; size_t len; } string_t; 

That everything is fine and dandy. But I want to be able to output the contents of this structure using a printf 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 needs an int , whereas I have size_t .

So the question is, how can I print a line using printf ?

+6
source share
3 answers

A simple solution would be to use unformatted output:

 fwrite(x.data, 1, x.len, stdout); 

This is a really 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) { } 

Make sure x.len not larger than SIZE_T_MAX .

+3
source

Assuming there are no embedded NUL characters in your string, you can use the %.*s specifier after pressing size_t on int :

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

This also assumes the string length is less than INT_MAX . If you have a line longer than INT_MAX , then you have other problems (it will take some time to print 2 billion characters).

+11
source

how can i print a string using printf?

In one call? You cannot in any meaningful way, since you say that you can have null terminators in unfamiliar places. In general, if your buffer may contain non-printable characters, you need to figure out how you want to print (or not) these characters when outputting your string. Write a loop, test each character and print it (or not), as your logic dictates.

+1
source

Source: https://habr.com/ru/post/955138/


All Articles