Ralph D. Ungermann wrote:
> Hal Vaughan wrote:
>> I have a series of codes that will include NULL bytes and other
>> non-text data that I need to send to a device through a file.
>
>> Since a NULL terminates a string
>
> Nope. But there is the concept of "Null-Terminated Byte Strings" (NTBS):
> many functions treat a '\0' as the end of the string.
In C, a string is terminated by a '\0' by definition (see n1256, the
latest C draft, section 7.1.1). If it isn't terminated by a '\0', it's
not a string.
>> Do I have to handle the string (or char[]) in a special way to make
>> sure all the data is kept intact?
>
> You must not use any of these NTBS functions, that's all.
>
> In C, an (un)signed char[] should be fine, and ordinary array
> initialization will work as expected:
> unsigned char dev_out[6] = { '\0x03', '\0', 0, 255, 'x', '\r' };
ITYM '\x03' above.
> I'm not aware of any sup****t for NUL in string literals, e.g.
> "abc\0def"; I'd just avoid it.
A conforming C implementation must allow it - n1256.pdf (the latest C
draft) has a footnote in 6.4.5p5 which says "A character string literal
need not be a string (see 7.1.1), because a null character may be
embedded in it by a \0 escape sequence." which makes it clear that '\0'
is allowed in string literals.
Nevertheless, a string literal may not be a good choice if it is to be
output as an array of bytes, because of the implicit '\0' at the end:
char foo[] = "ab\0cd";
is equivalent to:
char foo[] = {'a','b','\0','c','d','\0'};
but the trailing '\0' is made much clearer in the second.


|