簡體   English   中英

將printf和cout重定向到套接字

[英]Redirecting printf and cout to socket

我在想是否可以輕松地將printf或cout重定向到套接字?

我目前正在Windows VC ++中編程...

不,但是您可以使用sprintf系列功能:

// Make sure this buffer is big enough; if the maximum size isn't known, use
// _vscprintf or a dynamically allocated buffer if you want to avoid truncation
char buffer[2048];
_snprintf_s(buffer, sizeof(buffer), _TRUNCATE, "format %s etc.", args...);
send(mySocket, buffer, strlen(buffer)+1, 0);  // +1 for NUL terminator

請注意, _snprintf_s是僅Microsoft運行時的函數,因此,如果要編寫可移植的代碼,請在其他平台上使用snprintf代替。

在C ++中,您還可以使用std::ostringstream獲得類似的結果:

std::ostringstream buffer;
buffer << "test: " << myvar << somethingelse << etc;
send(mySocket, buffer.str().c_str(), buffer.str().size() + 1, 0);
                                                     // +1 for NUL terminator

不平凡。 在WinSock(MS Windows)中,世界套接字與文件描述符不同。

Linux具有dprintf(),它允許您寫入套接字文件描述符。

int dprintf(int fd, const char *format, ...);

http://linux.about.com/library/cmd/blcmdl3_dprintf.htm

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM