If it were me I would probably do something similar to this:
const std::size_t INIT_BUFFER_SIZE = 1024;
int main()
{
try
{
// on some systems you may need to reopen stdin in binary mode
// this is supposed to be reasonably portable
std::freopen(nullptr, "rb", stdin);
if(std::ferror(stdin))
throw std::runtime_error(std::strerror(errno));
std::size_t len;
std::array<char, INIT_BUFFER_SIZE> buf;
// somewhere to store the data
std::vector<char> input;
// use std::fread and remember to only use as many bytes as are returned
// according to len
while((len = std::fread(buf.data(), sizeof(buf[0]), buf.size(), stdin)) > 0)
{
// whoopsie
if(std::ferror(stdin) && !std::feof(stdin))
throw std::runtime_error(std::strerror(errno));
// use {buf.data(), buf.data() + len} here
input.insert(input.end(), buf.data(), buf.data() + len); // append to vector
}
// use input vector here
}
catch(std::exception const& e)
{
std::cerr << e.what() << '
';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Note you may need to re-open stdin
in binary mode not sure how portable that is but various documentation suggests is reasonably well supported across systems.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…