将 x00写入文件

Writing x00 into a file

本文关键字:文件 x00      更新时间:2023-10-16

我必须将十六进制命令发送到USB设备。

命令是:

echo -en "x1bx70x00x19xfa" > /dev/usb/lp0

如果我将其写在终端上,则可以工作。但是,在C 中,十六进制命令存在问题。x00被检测为null端端字符串。

我尝试了两种方法:

std::string cmd = "echo '\x1b\x70\x00\x19\xfa' > /dev/usb/lp0";
std::system(cmd.c_str());

什么也没发生。

和:

std::ofstream device;
device.open("/dev/usb/lp0");
device << "x1bx70x00x19xfa";
device.close();

该设备无能为力。

如何解决此问题并使用x00字符串?

使用 write函数编写固定长度的字节。

既然您正在编写二进制数据,我建议您也以二进制模式打开文件,并编写实际整数值而不是字符串。


示例代码

std::ofstream device ("/dev/usb/lp0",std::ofstream::binary);
std::uint8_t const message[] = { 0x1b, 0x70, 0x00, 0x19, 0xfa };
if (device)
    device.write(reinterpret_cast<char const*>(message), sizeof message);

我建议使用unsigned char的数组,而不是C-string或STD :: String,以存储命令:

const unsigned char usb_cmd[] = { 0x1b, 0x70, 0x00, 0x19, 0xfa };

这样,读者很明显,这是二进制协议中的一条消息,而不是文本而不是nul终止的字符串。另外,以这种方式声明,sizeof(usb_cmd)将是正确编写的字节数,而不是sizeof(char*)。如果您需要在运行时更改命令的内容,请改用vector<unsigned char>

我也将使用操作系统的原始词进行实际写入设备:

int fd = open("/dev/usb/lp0", O_RDWR);
if (fd == -1) {
    perror("/dev/usb/lp0");
    return -1;
}
ssize_t nwritten = write(fd, usb_cmd, sizeof usb_cmd);
if ((size_t)nwritten != sizeof usb_cmd) {
    if (nwritten < 0) {
        perror("/dev/usb/lp0: write error");
    } else {
        fprintf(stderr, "/dev/usb/lp0: short write (%zu of %zu bytes)n",
                (size_t)nwritten, sizeof usb_cmd);
    }
    close(fd);
    return -1;
}
close(fd);
return 0;

以这种方式,您可以确定一个准确的字节数是一次编写的;没有编码或缓冲层要干扰。