Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't stop printf at null termination (\0)

Tags:

c

printf

printf stops printing at the first \0 it meets.

Is there a way to force it to continue, for example if my string contains more characters after \0.

like image 520
bemug Avatar asked Dec 07 '25 02:12

bemug


2 Answers

If you know the length of your string as n characters, you can output it using fwrite:

if (n && fwrite(str, 1, n, stdout) != n) {
    /* Error handling. */
}
like image 90
orlp Avatar answered Dec 08 '25 18:12

orlp


No, not directly.

What you can do is put it in a loop

#include <stdio.h>

int main(void) {
    char test[] = "one\0two\0three\0four\0"; /* double NUL to terminate data */
    char *ptr = test;
    do {
        ptr += printf("%s\n", ptr); /* add string size + 1 (extra 1 from '\n') */
    } while (*ptr);
    return 0;
}
like image 36
pmg Avatar answered Dec 08 '25 16:12

pmg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!