简体   繁体   English

将printf和cout重定向到套接字

[英]Redirecting printf and cout to socket

I am thinking if it is possible to redirect printf or cout to a socket easily? 我在想是否可以轻松地将printf或cout重定向到套接字?

I am currently programming in Windows VC++ btw... 我目前正在Windows VC ++中编程...

No, but you can use the sprintf family of functions: 不,但是您可以使用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

Note that _snprintf_s is a Microsoft runtime-only function, so if you're writing portable code, use snprintf instead on other platforms. 请注意, _snprintf_s是仅Microsoft运行时的函数,因此,如果要编写可移植的代码,请在其他平台上使用snprintf代替。

In C++, you can also use a std::ostringstream for similar results: 在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

Not trivially. 不平凡。 In WinSock (MS Windows) world sockets are not the same as file descriptors. 在WinSock(MS Windows)中,世界套接字与文件描述符不同。

Linux has dprintf() which allows you to write to a socket file descriptor. Linux具有dprintf(),它允许您写入套接字文件描述符。

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

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM