将 printf 和 cout 重定向到套接字

Redirecting printf and cout to socket

本文关键字:套接字 重定向 cout printf      更新时间:2023-10-16

我在想是否有可能轻松地将 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

Linux 有 dprintf(),它允许你写入套接字文件描述符。

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

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

不是微不足道的。 在WinSock(MS Windows)中,世界套接字与文件描述符不同。