From 4ee6ff0a738374290a79ba280be44c01e33354cf Mon Sep 17 00:00:00 2001 From: m-holger Date: Mon, 6 Mar 2023 14:41:43 +0000 Subject: Add new procedure QUtil::read_file_into_string --- libqpdf/QUtil.cc | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'libqpdf/QUtil.cc') diff --git a/libqpdf/QUtil.cc b/libqpdf/QUtil.cc index 7f23bd03..bae067b6 100644 --- a/libqpdf/QUtil.cc +++ b/libqpdf/QUtil.cc @@ -1243,6 +1243,37 @@ QUtil::read_file_into_memory( } } +std::string +QUtil::read_file_into_string(char const* filename) +{ + FILE* f = safe_fopen(filename, "rb"); + FileCloser fc(f); + return read_file_into_string(f, filename); +} + +std::string +QUtil::read_file_into_string(FILE* f, std::string_view filename) +{ + fseek(f, 0, SEEK_END); + auto size = QIntC::to_size(QUtil::tell(f)); + fseek(f, 0, SEEK_SET); + std::string result(size, '\0'); + if (auto read = fread(result.data(), 1, size, f); read != size) { + if (ferror(f)) { + throw std::runtime_error( + std::string("failure reading file ") + std::string(filename) + + " into memory: read " + uint_to_string(read) + "; wanted " + + uint_to_string(size)); + } else { + throw std::runtime_error( + std::string("premature eof reading file ") + + std::string(filename) + " into memory: read " + + uint_to_string(read) + "; wanted " + uint_to_string(size)); + } + } + return result; +} + static bool read_char_from_FILE(char& ch, FILE* f) { -- cgit v1.2.3-70-g09d2