[英]Send std::stringstream in named pipe
我有一個 std::stringstream 類型的變量,我在其中以 blob 格式寫入數據,之后我想將其發送到 pipe,從這里數據被另一個應用程序接管並通過 tcp 套接字發送。 當我調用 std::stringstream.str() 時,它會向我顯示正確的信息。 如果我給 std::cout << std::stringstream.str().c_str() 會顯示空結果。 我試圖將 std::stringstream.str().c_str() 發送到 pipe 並在另一個應用程序中獲得一個空白空間。
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);
stream 變量的內容是圖中的那個: stream 變量的內容
我通過套接字接收一串字節,根據加密文檔對該內容進行解碼,應用一些過濾器,然后僅使用我需要的數據對其進行編碼。 它有很多帶有'\0'
區域,因為最后它必須具有相同的長度,以便在應用解碼文檔時它可以工作。 代碼很大很復雜,所以我無法顯示它。 該編碼內容看起來像圖片中的內容,我必須通過 pipe 將其發送到另一個應用程序。 我使用了std::stringstream
,因為在這里我可以根據加密文檔逐字節添加。 該變量中的寫入代碼是:
// The data is added like this:
int value = std::bitset<8>("00111101").to_ulong();
// or
int value = 80;
// and so on
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));
}
當你這樣做時:
std::cout << std::stringstream.str().c_str();
它試圖將數據解釋為 C 字符串,從圖像中我可以看出它顯然不是 C 字符串,因為它在很多地方都有 null 字符'\0'
。 Every C++ function that handles a C string will expect the string to be terminated by '\0'
, so it stops processing the as soon as it sees the null character. 當您使用std::string
(由.str()
返回)時,這不是問題,因為它存儲字符串的大小,並且不依賴 null 字符作為終止符。 對於std::string
, '\0'
並不特殊。
至於為什么在接收端看不到內容,我只能推測,因為您沒有提供代碼,但我假設您將數據作為 C 字符串( const char *
)處理,不是嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.