Search code examples
c++iobufferstdin

Fast read stdin into buffer with no checking


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?


Solution

  • 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;
    }