I have a small segment of C++ code that reads in unsigned char's
a block at a time and then for debugging purposes, outputs via std::cout
int fd;
ssize_t bytes_read {0};
unsigned char *buffer {new unsigned char[512]};
std::vector<unsigned char> *pMemory {new std::vector<unsigned char>(512)};
fd = open("/tmp/text.txt", O_RDONLY);
if (fd != -1)
{
do
{
bytes_read = read(fd, buffer, 512);
if (bytes_read > 0)
{
for (int i = 0; i < bytes_read; ++i) {
pMemory->emplace_back(buffer[i]);
}
}
} while (bytes_read > 0);
for (auto const& block : *pMemory)
{
std::cout << block;
}
std::cout << std::endl;
}
I have initialized the vector pMemory
with a block to prevent memory thrashing from each call to pMemory->emplace_back(buffer[i])
, but I am wondering if there is a more efficient way (perhaps by using iterators to move a range from the buffer
array ?), to move each chunk of memory in buffer
into a vector ?