【问题标题】:Fast read stdin into buffer with no checking无需检查即可快速将标准输入读入缓冲区
【发布时间】:2019-12-30 14:50:10
【问题描述】:

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

到目前为止,我有这个:

#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() 的东西可以快速读入缓冲区而不是控制台?

【问题讨论】:

  • 不确定我是否理解该请求。 fread 看起来像你想要的吗?
  • @AProgrammer 是的,fread 有效。我只是不知道您可以将标准输入作为 FILE* 传递。

标签: c++ io buffer stdin


【解决方案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 ] = '\0';

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

    return 0;
}

【讨论】:

  • 请注意 puts() 在末尾插入换行符。您可以使用fputs(buffer, stdout); 自己管理换行符。
【解决方案2】:

如果puts 为您提供了您想要的行为,除了它输出到标准输出这一事实,您可以使用dup2 将标准输出通过管道传输到不同的文件描述符(完成后不要忘记重新连接标准输出)。

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

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 2023-04-08
    • 2011-05-03
    • 1970-01-01
    相关资源
    最近更新 更多