diff options
author | Jay Berkenbilt <ejb@ql.org> | 2019-06-22 16:12:10 +0200 |
---|---|---|
committer | Jay Berkenbilt <ejb@ql.org> | 2019-06-22 16:14:25 +0200 |
commit | 1bde5c68a302c99c627f86d8c95226a8a7623ac3 (patch) | |
tree | a29bbd128894dd564375ecef0917da310ef1ee6d /libqpdf | |
parent | 658b5bb3be49d2666b91d35671de71c1cf0a5853 (diff) | |
download | qpdf-1bde5c68a302c99c627f86d8c95226a8a7623ac3.tar.zst |
Add QUtil::read_file_into_memory
This code was essentially duplicated between test_driver and
standalone_fuzz_target_runner.
Diffstat (limited to 'libqpdf')
-rw-r--r-- | libqpdf/QUtil.cc | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/libqpdf/QUtil.cc b/libqpdf/QUtil.cc index ddfc0cdb..151832fb 100644 --- a/libqpdf/QUtil.cc +++ b/libqpdf/QUtil.cc @@ -957,6 +957,45 @@ QUtil::read_lines_from_file(char const* filename) return lines; } +void +QUtil::read_file_into_memory( + char const* filename, + PointerHolder<char>& file_buf, size_t& size) +{ + FILE* f = safe_fopen(filename, "rb"); + fseek(f, 0, SEEK_END); + size = QIntC::to_size(QUtil::tell(f)); + fseek(f, 0, SEEK_SET); + file_buf = PointerHolder<char>(true, new char[size]); + char* buf_p = file_buf.getPointer(); + size_t bytes_read = 0; + size_t len = 0; + while ((len = fread(buf_p + bytes_read, 1, size - bytes_read, f)) > 0) + { + bytes_read += len; + } + if (bytes_read != size) + { + if (ferror(f)) + { + throw std::runtime_error( + std::string("failure reading file ") + filename + + " into memory: read " + + uint_to_string(bytes_read) + "; wanted " + + uint_to_string(size)); + } + else + { + throw std::runtime_error( + std::string("premature eof reading file ") + filename + + " into memory: read " + + uint_to_string(bytes_read) + "; wanted " + + uint_to_string(size)); + } + } + fclose(f); +} + std::list<std::string> QUtil::read_lines_from_file(std::istream& in) { |