Add new procedure QUtil::read_file_into_string

This commit is contained in:
m-holger 2023-03-06 14:41:43 +00:00
parent 4359de9038
commit 4ee6ff0a73
5 changed files with 45 additions and 4 deletions

View File

@ -485,6 +485,11 @@ namespace QUtil
void read_file_into_memory(
char const* filename, std::shared_ptr<char>& file_buf, size_t& size);
QPDF_DLL
std::string read_file_into_string(char const* filename);
QPDF_DLL
std::string read_file_into_string(FILE* f, std::string_view filename = "");
// This used to be called strcasecmp, but that is a macro on some
// platforms, so we have to give it a name that is not likely to
// be a macro anywhere.

View File

@ -760,11 +760,9 @@ QPDFJob::Config::showObject(std::string const& parameter)
QPDFJob::Config*
QPDFJob::Config::jobJsonFile(std::string const& parameter)
{
std::shared_ptr<char> file_buf;
size_t size;
QUtil::read_file_into_memory(parameter.c_str(), file_buf, size);
try {
o.initializeFromJson(std::string(file_buf.get(), size), true);
o.initializeFromJson(
QUtil::read_file_into_string(parameter.c_str()), true);
} catch (std::exception& e) {
throw std::runtime_error(
"error with job-json file " + std::string(parameter) + ": " +

View File

@ -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)
{

File diff suppressed because one or more lines are too long

View File

@ -576,6 +576,12 @@ read_from_file_test()
auto buf2 = b2.getBufferSharedPointer();
assert(buf2->getSize() == size);
assert(memcmp(buf2->getBuffer(), p, size) == 0);
auto s = QUtil::read_file_into_string("other-file");
std::cout << "read " << s.size() << " bytes" << std::endl;
assert(s.size() == 24652);
assert(s.substr(0, 36) == "This file is used for qutil testing.");
assert(s.substr(24641, 10) == "very long.");
}
void