gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:22:23 26 4
gpt4 key购买 nike

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

最佳答案

您可以使用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;
}

关于c++ - 无需检查即可将标准输入快速读入缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59532679/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com