我有缓冲区,比如说65536字节长。如何在不检查换行符或'\ 0'字符的情况下,如何尽快(使用IO硬件)将stdin读入该缓冲区。我保证stdin中的字符数将始终与缓冲区匹配。 到目前为止,我有这个: 是否有类似于 答案 0 :(得分:1) 您可以使用C的标准 答案 1 :(得分:0) 如果#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 个答案:
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;
}
puts
除了输出到stdout的事实以外,还提供了您想要的行为,则可以使用dup2
将stdout传递到其他文件描述符(不要忘记在重新连接stdout时您完成了。)