在 C++ 中处理标准输入中的空字符
Dealing with null characters in stdin in C++
我正在为 Chrome 编写一个使用本机主机消息传递的扩展。目标是 Chrome 在 OS 默认浏览器中打开链接 运行 在应用程序模式下。 Chrome 通过管道实现本机主机消息传递到本机应用程序的标准输入和标准输出。这一切都很好,我已经得到了与本机应用程序对话的扩展。我遇到的问题是前 4 个字节的数据包含以下字符串的长度,对于我来说,它始终包含空字符。示例 strace 如下所示。处理这个问题的最佳方法是什么?我想使用 cin 或 getline 之类的东西,如果可能的话,它们会暂停程序直到收到输入。
Process 27964 attached
read(0, "~[=10=][=10=][=10=]\"http://whosebug.com/qu"..., 4096) = 130
read(0,
这是当前的 C++ 代码。我尝试过使用 cin.get 和 fgets 的变体,但它们不等待输入,并且 Chrome 在循环运行异常后终止程序。
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
for(;;) {
string message;
cin >> message;
if(!message.length()) break;
string cmd(string("xdg-open ") + message);
system(cmd.c_str());
}
return 0;
}
据我了解 here,长度应为本机字节顺序,因此您的编译器对相同 CPU 架构使用相同的字节顺序:
each message is serialized using JSON, UTF-8 encoded and is preceded
with 32-bit message length in native byte order.
这意味着您可以先阅读长度:
uint32_t len;
while (cin.read(reinterpret_cast<char*>(&len), sizeof (len))) // process the messages
{
// you know the number of bytes in the message: just read them
string msg (len, ' '); // string filled with blanks
if (!cin.read(&msg[0], len) )
/* process unexpected error of missing bytes */;
else /* process the message normally */
}
我正在为 Chrome 编写一个使用本机主机消息传递的扩展。目标是 Chrome 在 OS 默认浏览器中打开链接 运行 在应用程序模式下。 Chrome 通过管道实现本机主机消息传递到本机应用程序的标准输入和标准输出。这一切都很好,我已经得到了与本机应用程序对话的扩展。我遇到的问题是前 4 个字节的数据包含以下字符串的长度,对于我来说,它始终包含空字符。示例 strace 如下所示。处理这个问题的最佳方法是什么?我想使用 cin 或 getline 之类的东西,如果可能的话,它们会暂停程序直到收到输入。
Process 27964 attached
read(0, "~[=10=][=10=][=10=]\"http://whosebug.com/qu"..., 4096) = 130
read(0,
这是当前的 C++ 代码。我尝试过使用 cin.get 和 fgets 的变体,但它们不等待输入,并且 Chrome 在循环运行异常后终止程序。
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
for(;;) {
string message;
cin >> message;
if(!message.length()) break;
string cmd(string("xdg-open ") + message);
system(cmd.c_str());
}
return 0;
}
据我了解 here,长度应为本机字节顺序,因此您的编译器对相同 CPU 架构使用相同的字节顺序:
each message is serialized using JSON, UTF-8 encoded and is preceded with 32-bit message length in native byte order.
这意味着您可以先阅读长度:
uint32_t len;
while (cin.read(reinterpret_cast<char*>(&len), sizeof (len))) // process the messages
{
// you know the number of bytes in the message: just read them
string msg (len, ' '); // string filled with blanks
if (!cin.read(&msg[0], len) )
/* process unexpected error of missing bytes */;
else /* process the message normally */
}