4Manuals

  • PDF Cloud HOME

无需检查即可将标准输入快速读入缓冲区 Download

    获取Hough线的交点OpenCV C ++ 如何将字符串“ text1”设置为包含项目text1,text2,test3的组合框的选定项目? 为什么System.Net.Mail.MailAddress构造函数在域部分中解析带有斜杠“ /”的电子邮件? Android 10,API29:在应用程序文件夹中使用C ++库编写文件会使应用程序崩溃 Unity-LineRenderer没有出现在版本(2D)上 按下按钮后,电话中未显示通知 ASP.net,使用WebConfig httpErrors重定向到区域内的控制器不起作用 获取会议室详细信息 我们如何将参数Line转换为Station? 网络核心:查找实体框架核心的主键和反射

我有缓冲区,比如说65536字节长。如何在不检查换行符或'\ 0'字符的情况下,如何尽快(使用IO硬件)将stdin读入该缓冲区。我保证stdin中的字符数将始终与缓冲区匹配。

到目前为止,我有这个:

#include <iostream>
#include <stdio.h>

#define BUFFER_LENGTH 65536

int main()
{
    std::ios::sync_with_stdio(false);
    setvbuf(stdout, NULL, _IONBF, BUFFER_LENGTH);

    char buffer[BUFFER_LENGTH];

    // now read stdin into buffer
    // fast print:
    puts(buffer);    // given buffer is null terminated

    return 0;
}

是否有类似于puts()的东西可以快速读入缓冲区而不是控制台?

2 个答案:

答案 0 :(得分:1)

您可以使用C的标准fread() function:

#include <iostream>
#include <stdio.h>

#define BUFFER_LENGTH 65536

int main()
{
    std::ios::sync_with_stdio(false);
    setvbuf(stdout, NULL, _IONBF, BUFFER_LENGTH);

    // need space to terminate the C-style string
    char buffer[BUFFER_LENGTH + 1];

    // eliminate stdin buffering too
    setvbuf(stdin, NULL, _IONBF, BUFFER_LENGTH);    

    // now read stdin into buffer
    size_t numRead = fread( buffer, 1, BUFFER_LENGTH, stdin );

    // should check for errors/partial reads here

    // fread() will not terminate any string so it
    // has to be done manually before using puts()
    buffer[ numRead ] = '';

    // fast print:
    puts(buffer);    // given buffer is null terminated

    return 0;
}

答案 1 :(得分:0)

如果puts除了输出到stdout的事实以外,还提供了您想要的行为,则可以使用dup2将stdout传递到其他文件描述符(不要忘记在重新连接stdout时您完成了。)

This post显示了一个用C重定向输出的好例子,而this post有一个获取内存中的缓冲区的文件描述符的例子。



Similar searches
    如何在保留旧参数的同时添加参数URL? 将TabGroup添加到窗口 尝试使用Struts2.5(服务器端)和Emberjs(客户端)构建CRUD应用程序时出错 错误:`style`属性需要从样式属性到值而不是字符串的映射 API因限制和偏移量而超时