在命名管道中发送std :: stringstream

问题描述 投票:0回答:2

我有一个std :: stringstream类型的变量,我在其中以blob格式写入数据,之后我想将其发送到管道,然后从此处将数据由另一个应用程序接管并通过tcp套接字发送。当我调用std :: stringstream.str()时,它向我显示了正确的信息。如果我给std :: cout << std :: stringstream.str()。c_str()显示空结果。我试图将std :: stringstream.str()。c_str()发送到管道,并在另一个应用程序中获得一个空白空间。

std::stringstream stream;
int fd;
const char* fifo = "/tmp/adpluspipe";

/* create the FIFO (named pipe) */
mkfifo(fifo, 0666);

/* write data to the FIFO */
fd = open(fifo, O_WRONLY);
write(fd, stream.str().data(), 84);
close(fd);

/* remove the FIFO */
unlink(fifo);

流变量的内容是图像中的内容:content of the stream variable

c++
2个回答
1
投票

[执行时:

std::cout << std::stringstream.str().c_str();

它试图将数据解释为C字符串,从图像中我可以清楚地看到它不是C字符串,因为它在许多地方都具有空字符'\0'。每个处理C字符串的C ++函数都希望该字符串以'\0'终止,因此一旦看到空字符,它将立即停止处理。当您使用std::string(由.str()返回)时,这不是问题,因为它存储字符串的大小,并且不依赖于空字符作为终止符。对于std::string'\0'不特殊。

关于为什么您看不到接收方的内容,我只能推测,因为您没有提供代码,但是我假设您将数据作为C字符串(const char *)处理,不?


0
投票

您的意思是有道理的。我通过套接字收到一个字节字符串,我根据加密文档对内容进行解码,应用了一些过滤器,然后仅使用所需的数据对其进行编码。它的许多区域都带有'\0',因为最后它必须具有相同的长度,以便在应用解码文档时它可以工作。该代码非常大且复杂,因此无法显示。编码的内容看起来像图片中的内容,我必须通过管道将其发送到另一个应用程序。我使用了std::stringstream,因为在这里我能够根据加密文档逐字节添加。该变量中的写代码为:

void writeBytes(std::stringstream &stream, int value, int valueSize)
{
    unsigned char bytes[valueSize];

    if(valueSize == 1){
        bytes[0] = value & 0xFF;
    }

    if(valueSize == 2){
        bytes[0] = (value >> 8) & 0xFF;
        bytes[1] = value & 0xFF;
    }

    if(valueSize == 4){
        bytes[0] = (value >> 24) & 0xFF;
        bytes[1] = (value >> 16) & 0xFF;
        bytes[2] = (value >> 8) & 0xFF;
        bytes[3] = value & 0xFF;
    }

    stream.write(reinterpret_cast<char*>(&bytes), sizeof(bytes));

    memset(bytes, 0, sizeof(bytes));

}
© www.soinside.com 2019 - 2024. All rights reserved.