[英]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, ...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.