Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf with %s to include null characters

Tags:

c

string

printf

I need to concatenate some strings, and I need to include NULL bytes. I don't want to treat a '\0' as a terminating byte. I want to save my valuable NULL bytes!

In a code example, if

    char *a = "\0hey\0\0";

I need to printf in a format that will output "\0hey\0\0".

-AUstin

like image 467
austin Avatar asked May 23 '11 06:05

austin


1 Answers

How about:

int i;
for(i = 0; i < 4; i++)
    printf("%c", a[i]);

If you want a 'printf-like' function to use this when you specify %s in a format string you could include the above code in your own function. But as @Neil mentioned, you'll struggle finding an alternative to looking for null bytes to determine the length of strings. For that I guess you could use some kind of escape character.

like image 138
sje397 Avatar answered Sep 30 '22 07:09

sje397