Created
March 28, 2021 16:14
-
-
Save BlackthornYugen/40067e8e1eaea126973b1041e70f857f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <iostream> | |
#include <vector> | |
static const int BUFFER_READ_SIZE = 8; | |
static const int MAX_READ_SIZE = 4 * 1024 * 1024; // 4MiB | |
int main() { | |
std::vector<char> echoData; | |
char stdinBuffer[BUFFER_READ_SIZE]; | |
FILE *standardInput = fdopen(0, "rb"); | |
int bufferBytesToSave; | |
// Keep looping while we are within the MAX_READ_SIZE and there are bytes in | |
// the buffer | |
while ((echoData.size() < MAX_READ_SIZE) && | |
(bufferBytesToSave = fread(&stdinBuffer[0], sizeof stdinBuffer[0], | |
BUFFER_READ_SIZE, standardInput))) { | |
// Loop until we have written all the bytes written to the buffer AND this | |
// buffer doesn't take us beyond MAX_READ_SIZE. I am intentionally checking | |
// in both places. There is probably an optimization to calculate and use: | |
// (MAX_READ_SIZE - (echoData.size + bufferBytesToSave))? | |
for (int i = 0; i < bufferBytesToSave && echoData.size() < MAX_READ_SIZE; | |
i++) { | |
echoData.push_back(stdinBuffer[i]); | |
} | |
} | |
// trim trailing newline | |
if (echoData.back() == 0x0a) { | |
echoData.pop_back(); | |
} | |
// write echoData | |
for (const auto &datum : echoData) { | |
std::cout << datum; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment