I am thinking if it is possible to redirect printf or cout to a socket easily?
I am currently programming in Windows VC++ btw...
No, but you can use the sprintf
family of functions:
// 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.
In C++, you can also use a std::ostringstream
for similar results:
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.
Linux has dprintf() which allows you to write to a socket file descriptor.
int dprintf(int fd, const char *format, ...);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.