printf 从 %s 包容 null 符号

我需要结合一些线路,我需要打开 NULL 字节。 我不想考虑 '\0 ' 作为最后的字节。 我想拯救我的宝贵价格 NULL 字节!

在代码的示例中,如果


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


我需要 printf 以输出的格式 "\0hey\0\0".

-AUstin
已邀请:

窦买办

赞同来自:

关于什么:


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


如果你想要一个函数 'printf-like' 指定时使用它
%s

在格式字符串中,您可以将上述代码启用到您自己的函数中。 但是,如上所述,您很难找到搜索的替代品。 null 字节确定线的长度。 为此,我认为你可以使用某种屏蔽符号。

郭文康

赞同来自:

这里的问题是字符串长度
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.

替代方案不使用带有空端的行,而是实现用于存储字节的替代机制; 例如,具有长度编码的阵列。


#include <stdio.h>

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

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

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


除非,但是,我希望你理解这个想法。

编辑: 2011-05-31

重读这个问题,我刚注意到这个词 "concatenate". 如果一个 NULL 必须将符号从内存中的一个位置准确地复制到另一个位置。 /不是反向斜线屏蔽/, 而且您提前知道每个阵列中的总字节数,那么您只需使用
http://linux.die.net/man/3/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 */
}


</string.h></stdio.h>

郭文康

赞同来自:

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

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

int i=0;
int j=0;
while/ i<bufsize &&="" ;="" ;[="" <="" a[j]="\0" buf="" buf[i++]="a[j++];" code]="" div="" else="" if="" j++;="" j<alen="" printf="" {="" }="">
</bufsize>

要回复问题请先登录注册