将 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
Linux 有 dprintf(),它允许你写入套接字文件描述符。
int dprintf(int fd, const char *format, ...);
http://linux.about.com/library/cmd/blcmdl3_dprintf.htm
不是微不足道的。 在WinSock(MS Windows)中,世界套接字与文件描述符不同。
相关文章:
- 当套接字连接断开时检测C/C++Unix
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- 套接字读取后,我在缓冲区中看到意外输入
- 如何在CPP中创建应该在Windows和Linux上运行的套接字?
- 我可以与 python 服务器而不是 c++ 客户端建立 tcp/ip 套接字吗?
- 套接字连接"Operation not permitted"错误,甚至使用升压/平发器根.cpp
- WINAPI 注册应用程序重新启动时不清除打开的套接字
- (Winsock) UDP 接收工作正常,但同一套接字的发送失败
- MSG_WAITALL的套接字发送得到了 22 EINVAL
- C++套接字客户端到 Python 服务器未创建连接
- 在不知道套接字的情况下关闭网络连接
- C++套接字对不读/写父/子
- 当客户端在 write() 期间终止连接时,由对等套接字错误重置连接
- 网络tcp套接字应用程序重试方法
- 将 printf 和 cout 重定向到套接字
- zeromq:重置REQ/REP套接字状态
- Android,ADB,将STDOUT重定向到套接字
- 使用套接字重定向