【发布时间】:2012-05-08 03:03:41
【问题描述】:
我在想是否可以轻松地将 printf 或 cout 重定向到套接字?
顺便说一句,我目前正在使用 Windows VC++ 编程...
【问题讨论】:
标签: c++ windows sockets printf
我在想是否可以轻松地将 printf 或 cout 重定向到套接字?
顺便说一句,我目前正在使用 Windows VC++ 编程...
【问题讨论】:
标签: c++ windows sockets printf
不,但您可以使用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
【讨论】:
dprintf 怎么样?行得通吗?
Linux 有 dprintf(),它允许您写入套接字文件描述符。
int dprintf(int fd, const char *format, ...);
【讨论】:
不简单。在 WinSock (MS Windows) 世界中,套接字与文件描述符不同。
【讨论】: