如何不为null终止缓冲区? [英] how to not null terminate a buffer?

查看:111
本文介绍了如何不为null终止缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想知道是否有办法在缓冲区中保留一个空字节吗?

Basically I want to know if there is a way to keep a null byte in a buffer?

示例:

#include <stdio.h>

int main()
{
    char buf[] = "hello there\x00, Hi";
    printf("%s\n", buf);

    return 0;
}

不幸的是,如果您在上面编译,您将获得的输出仅为 hello (空值由 \ x00 终止).那么有没有办法将空字节保留在堆栈中并在之后获得 Hi ?

Unfortunately, if you compile above, the output you would get is hello there only (null terminated by \x00). So is there there a way to keep the null byte in the stack and get the Hi after that too?

仅供参考,如果您想建议使用 \\ x00 转义 \ ,我不能这样做.

FYI, if you wanted to recommend to escape \ with \\x00, I can't do that.

推荐答案

根据定义,C字符串不能包含NUL字节,后者明确保留为终止字符.如果需要支持的原始缓冲区,则不能使用C字符串.您将需要区别对待.所有以 str 开头的C字符串函数在这里都是禁止使用的.

C strings by definition cannot incorporate NUL bytes, that is explicitly reserved as a terminating character. If you need a raw buffer that does support that then you can't use a C string. You will need to treat it differently. All of the C string functions starting with str are off-limits here.

printf 将终止于NUL字节.如果要打印整个缓冲区,则需要使用较低级别的工具,例如 fwrite .

printf with %s will of course terminate on the NUL byte. If you want to print the whole buffer then you need to use lower-level tools like fwrite.

这篇关于如何不为null终止缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆