Reputation: 1907
I have buffer, let's say 65536 bytes long. How can I read stdin into that buffer as fast as possible (using IO hardware) without any check for newline or '\0' characters. I have a guarantee that the number of characters in stdin will always match my buffer.
So far I have this:
#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;
}
Is there something similar to puts()
that will fast read into buffer instead of console?
Upvotes: 1
Views: 851
Reputation: 1
You can use C's standard 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;
}
Upvotes: 1
Reputation: 130
If puts
gives you the behavior you want except for the fact that it outputs to stdout, you could use dup2
to pipe stdout to a different file descriptor (don't forget to reconnect stdout when you're done).
This post shows a good example of redirecting output in C, and this post has an example of getting a file descriptor for a buffer in memory.
Upvotes: 0