Skip to content

Instantly share code, notes, and snippets.

@neilmayhew
Created February 17, 2017 17:07
Show Gist options
  • Save neilmayhew/22fc0e094270aba4c558187582c709b7 to your computer and use it in GitHub Desktop.
Save neilmayhew/22fc0e094270aba4c558187582c709b7 to your computer and use it in GitHub Desktop.
Read a file into a vector using C++11
#include <cstring> // For strerror
#include <list>
#include <memory>
#include <vector>
#include <stdexcept>
#include <unistd.h> // For read
std::vector<unsigned char> readfile(int fd)
{
struct Chunk
{
size_t used;
unsigned char data[16*1024];
Chunk() : used(0) {}
void fill(int fd)
{
while (used < sizeof(data))
{
ssize_t n = read(fd, data + used, sizeof(data) - used);
if (n < 0)
throw std::runtime_error(std::strerror(errno));
used += n;
if (n == 0)
break;
}
}
};
std::list<std::unique_ptr<Chunk>> chunks;
size_t count = 0;
for (;;)
{
std::unique_ptr<Chunk> c(new Chunk);
c->fill(fd);
if (!c->used)
break;
count += c->used;
chunks.push_back(std::move(c));
}
std::vector<unsigned char> v(count);
unsigned char* next = v.data();
for (const auto& c : chunks)
{
std::copy(c->data, c->data + c->used, next);
next += c->used;
}
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment