【问题标题】:Redirecting printf and cout to socket将 printf 和 cout 重定向到套接字
【发布时间】:2012-05-08 03:03:41
【问题描述】:

我在想是否可以轻松地将 printf 或 cout 重定向到套接字?

顺便说一句,我目前正在使用 Windows VC++ 编程...

【问题讨论】:

    标签: c++ windows sockets printf


    【解决方案1】:

    不,但您可以使用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
    

    【讨论】:

    • @PauloBu 直接使用dprintf 怎么样?行得通吗?
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      不简单。在 WinSock (MS Windows) 世界中,套接字与文件描述符不同。

      【讨论】:

        猜你喜欢
        • 2011-06-26
        • 1970-01-01
        • 1970-01-01
        • 2019-05-27
        • 2011-12-27
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        相关资源
        最近更新 更多