printf with%s包含空字符

时间:2011-05-23 06:36:49

标签: c string printf

我需要连接一些字符串,我需要包含NULL字节。我不想将'\ 0'视为终止字节。我想保存我宝贵的NULL字节!

在代码示例中,如果

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

我需要以输出“\ 0hey \ 0 \ 0”的格式打印。

-AUstin

3 个答案:

答案 0 :(得分:12)

怎么样:

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

如果您希望在格式字符串中指定%s时使用“类似printf”的函数,则可以在自己的函数中包含上述代码。但正如@Neil所提到的,你将很难找到寻找空字节来确定字符串长度的替代方法。为此,我猜你可以使用某种转义字符。

答案 1 :(得分:7)

这里的问题是字符串a的长度不容易确定。例如,您的代码..

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

..为字符串分配七个字节,最后一个是NULL终止符。使用像strlen这样的函数会返回0。

如果您知道字符串的精确长度,那么您可以编写或迭代字节:

#ifdef ESCAPE_NULLS
    int i;
    for (i = 0; i <= 6; i++)
        if (a[i] == 0)
            printf("\\0");
        else
            printf("%c", a[i]);
#else
    write(1, a, 6);
#endif

但你必须知道6。

另一种方法是不使用以NULL结尾的字符串,而是为您的字节实现替代存储机制;例如,长度编码的数组。

#include <stdio.h>

typedef struct {
    int length;
    char *bytes;
} bytearr;

void my_printf(bytearr *arr)
{
    #ifdef ESCAPE_NULLS
        int i;
        for (i = 0; i <= arr->length; i++)
            if (arr->bytes[i] == 0)
                printf("\\0");
            else
                printf("%c", arr->bytes[i]);
    #else
        write(1, arr->bytes, arr->length);
    #endif
}

void main(void)
{
    bytearr foo = {
        6, "\0hey\0\0"
    };
    my_printf(&foo);
}

没有优雅,但希望你明白了。

编辑:2011-05-31

重读我刚刚注意到“连接”这个词的问题。如果要将NULL字符忠实地从内存中的一个位置复制到另一个位置(不是反斜杠转义),并且您事先知道每个数组中的总字节数,那么您只需使用memcpy

#include <string.h>
char *a = "\0hey\0\0";   /*  6 */
char *b = "word\0up yo"; /* 10 */
char *c = "\0\0\0\0";    /*  4 */
void main(void)
{
    char z[20];
    char *zp = z;
    zp = memcpy(zp, a, 6);
    zp = memcpy(zp, b, 10);
    zp = memcpy(zp, c, 4);
    /* now z contains all 20 bytes, including 8 NULLs */
}

答案 2 :(得分:0)

char *a="\0hey\0\0";
int alen = 7;

char buf[20] = {0};
int bufSize = 20;

int i=0;
int j=0;
while( i<bufSize && j<alen )
{
    if(a[j]=='\0') {
        buf[i++]='\\';
        buf[i++]='0';
        j++;
    }
    else {
        buf[i++] = a[j++];
    }
}

printf(buf);