无需检查即可将标准输入快速读入缓冲区
Fast read stdin into buffer with no checking
我有缓冲区,比如说 65536 字节长。如何在不检查换行符或“\0”字符的情况下尽可能快地将标准输入读入该缓冲区(使用 IO 硬件)。我保证 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()
的东西可以快速读入缓冲区而不是控制台?
如果 puts
给你想要的行为,除了它输出到标准输出的事实,你可以使用 dup2
将标准输出通过管道传输到不同的文件描述符(不要忘记重新连接完成后的标准输出)。
This post shows a good example of redirecting output in C, and this post 有一个为内存中的缓冲区获取文件描述符的示例。
你可以使用 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 ] = '[=10=]';
// fast print:
puts(buffer); // given buffer is null terminated
return 0;
}
我有缓冲区,比如说 65536 字节长。如何在不检查换行符或“\0”字符的情况下尽可能快地将标准输入读入该缓冲区(使用 IO 硬件)。我保证 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()
的东西可以快速读入缓冲区而不是控制台?
如果 puts
给你想要的行为,除了它输出到标准输出的事实,你可以使用 dup2
将标准输出通过管道传输到不同的文件描述符(不要忘记重新连接完成后的标准输出)。
This post shows a good example of redirecting output in C, and this post 有一个为内存中的缓冲区获取文件描述符的示例。
你可以使用 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 ] = '[=10=]';
// fast print:
puts(buffer); // given buffer is null terminated
return 0;
}