io: add FILE slurp overload

This commit is contained in:
Danny Robson 2015-10-29 17:52:19 +11:00
parent 4aeacc3a27
commit 620c2d3eb1
2 changed files with 31 additions and 2 deletions

27
io.cpp
View File

@ -72,6 +72,33 @@ util::slurp (const boost::filesystem::path& path) {
}
//-----------------------------------------------------------------------------
std::vector<char>
util::slurp (FILE *stream)
{
std::vector<char> data;
data.resize (16);
for (size_t chunk = 0, size = data.size ();
!ferror (stream) && !feof (stream);
chunk = size, size *= 2u)
{
auto found = fread (data.data () + chunk, 1, chunk, stream);
if (found != chunk)
break;
data.resize (data.size () * 2u);
}
if (ferror (stream))
errno_error::throw_code ();
CHECK (feof (stream));
return data;
}
//-----------------------------------------------------------------------------
void
util::write (const fd &out,

6
io.hpp
View File

@ -70,10 +70,12 @@ namespace util {
/// Reads an entire file into memory. Caller frees the result. Guarantees a
/// null trailing byte.
std::vector<char>
slurp [[gnu::warn_unused_result]] (const boost::filesystem::path&);
std::vector<char> slurp (const boost::filesystem::path&);
std::vector<char> slurp (FILE *);
//-------------------------------------------------------------------------
void write (const fd&, const void *restrict data, size_t bytes);
template <typename T>