将 x00写入文件
Writing x00 into a file
我必须将十六进制命令发送到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;
以这种方式,您可以确定一个准确的字节数是一次编写的;没有编码或缓冲层要干扰。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- 将 x00写入文件