Commit ab4061f1ee4e71a586f60bd65b9be4c96bf0bed8

Authored by Jay Berkenbilt
1 parent 211a7f57

Add error detection for read_lines_from_file(FILE*)

Showing 1 changed file with 17 additions and 3 deletions
libqpdf/QUtil.cc
... ... @@ -1043,6 +1043,20 @@ QUtil::read_file_into_memory(
1043 1043 fclose(f);
1044 1044 }
1045 1045  
  1046 +static bool read_char_from_FILE(char& ch, FILE* f)
  1047 +{
  1048 + auto len = fread(&ch, 1, 1, f);
  1049 + if (len == 0)
  1050 + {
  1051 + if (ferror(f))
  1052 + {
  1053 + throw std::runtime_error("failure reading character from file");
  1054 + }
  1055 + return false;
  1056 + }
  1057 + return true;
  1058 +}
  1059 +
1046 1060 std::list<std::string>
1047 1061 QUtil::read_lines_from_file(char const* filename)
1048 1062 {
... ... @@ -1050,7 +1064,7 @@ QUtil::read_lines_from_file(char const* filename)
1050 1064 std::list<std::string> lines;
1051 1065 FILE* f = safe_fopen(filename, "rb");
1052 1066 FileCloser fc(f);
1053   - auto next_char = [&f](char& ch) { return (fread(&ch, 1, 1, f) > 0); };
  1067 + auto next_char = [&f](char& ch) { return read_char_from_FILE(ch, f); };
1054 1068 read_lines_from_file(next_char, lines, false);
1055 1069 return lines;
1056 1070 }
... ... @@ -1061,7 +1075,7 @@ QUtil::read_lines_from_file(char const* filename, bool preserve_eol)
1061 1075 std::list<std::string> lines;
1062 1076 FILE* f = safe_fopen(filename, "rb");
1063 1077 FileCloser fc(f);
1064   - auto next_char = [&f](char& ch) { return (fread(&ch, 1, 1, f) > 0); };
  1078 + auto next_char = [&f](char& ch) { return read_char_from_FILE(ch, f); };
1065 1079 read_lines_from_file(next_char, lines, preserve_eol);
1066 1080 return lines;
1067 1081 }
... ... @@ -1089,7 +1103,7 @@ std::list&lt;std::string&gt;
1089 1103 QUtil::read_lines_from_file(FILE* f, bool preserve_eol)
1090 1104 {
1091 1105 std::list<std::string> lines;
1092   - auto next_char = [&f](char& ch) { return (fread(&ch, 1, 1, f) > 0); };
  1106 + auto next_char = [&f](char& ch) { return read_char_from_FILE(ch, f); };
1093 1107 read_lines_from_file(next_char, lines, preserve_eol);
1094 1108 return lines;
1095 1109 }
... ...