From 5b0ea5e95c154f8d13dc177e9999e2694a67a018 Mon Sep 17 00:00:00 2001 From: ToruNiina Date: Sun, 30 Jun 2024 00:29:34 +0900 Subject: [PATCH] fix #249: make sure all the file content is read --- include/toml11/parser.hpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/include/toml11/parser.hpp b/include/toml11/parser.hpp index 66948cd..1622ae8 100644 --- a/include/toml11/parser.hpp +++ b/include/toml11/parser.hpp @@ -3524,7 +3524,7 @@ try_parse(std::istream& is, std::string fname = "unknown file", spec s = spec::d // read whole file as a sequence of char assert(fsize >= 0); - std::vector letters(static_cast(fsize)); + std::vector letters(static_cast(fsize), '\0'); is.read(reinterpret_cast(letters.data()), fsize); return detail::parse_impl(std::move(letters), std::move(fname), std::move(s)); @@ -3714,7 +3714,15 @@ try_parse(FILE* fp, std::string filename, spec s = spec::default_version()) // read whole file as a sequence of char assert(fsize >= 0); std::vector letters(static_cast(fsize)); - std::fread(letters.data(), sizeof(char), static_cast(fsize), fp); + const auto actual = std::fread(letters.data(), sizeof(char), static_cast(fsize), fp); + if(actual != fsize) + { + return err(std::vector{error_info( + std::string("File size changed: \"") + filename + + std::string("\" make sure that FILE* is in binary mode " + "to avoid LF <-> CRLF conversion"), {} + )}); + } return detail::parse_impl(std::move(letters), std::move(filename), std::move(s)); } @@ -3752,7 +3760,12 @@ parse(FILE* fp, std::string filename, spec s = spec::default_version()) // read whole file as a sequence of char assert(fsize >= 0); std::vector letters(static_cast(fsize)); - std::fread(letters.data(), sizeof(char), static_cast(fsize), fp); + const auto actual = std::fread(letters.data(), sizeof(char), static_cast(fsize), fp); + if(actual != fsize) + { + throw file_io_error(errno, "File size changed; make sure that " + "FILE* is in binary mode to avoid LF <-> CRLF conversion", filename); + } auto res = detail::parse_impl(std::move(letters), std::move(filename), std::move(s)); if(res.is_ok())