将\ x00写入文件

时间:2018-02-12 16:39:17

标签: c++ hex

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

命令是:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

  <xsl:template match="node[three = 1]">
      <xsl:copy-of select="../node[three = 2]"/>
  </xsl:template>

  <xsl:template match="node[three = 2]">
      <xsl:copy-of select="../node[three = 1]"/>
  </xsl:template>

</xsl:transform>

如果我在终端上写它,它可以工作。但是,在C ++中,hex命令存在问题。 echo -en "\x1b\x70\x00\x19\xfa" > /dev/usb/lp0 被检测为以空字符结尾的字符串。

我尝试了两种方法:

\x00

什么都没发生。

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 << "\x1b\x70\x00\x19\xfa"; device.close(); 字符串?

2 个答案:

答案 0 :(得分:7)

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

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

示例代码

ApplicationDbContext

答案 1 :(得分:3)

我建议使用unsigned char数组,而不是C字符串或std :: string来存储命令:

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

这种方式对读者来说很明显,这是二进制协议中的消息,而不是文本而不是以空字符结尾的字符串。此外,以这种方式声明,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;

这样,您可以确保一次写入正确的字节数;没有编码或缓冲层来干扰。