Skip to content

Commit e637371

Browse files
committed
Properly cast the result of tellg() and handle filesystem errors more gracefully.
1 parent a794682 commit e637371

1 file changed

Lines changed: 18 additions & 2 deletions

File tree

cppwinrt/text_writer.h

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,24 @@ namespace cppwinrt
1414
inline std::string file_to_string(std::string const& filename)
1515
{
1616
std::ifstream file(filename, std::ios::binary | std::ios::ate);
17-
const auto size = file.tellg();
17+
if (!file) { return{}; }
18+
19+
const auto stream_size = file.tellg();
20+
if (stream_size == std::ifstream::pos_type(-1))
21+
{
22+
return {};
23+
}
24+
1825
file.seekg(0);
26+
27+
auto size = static_cast<std::size_t>(stream_size);
1928
std::string result(size, '\0');
2029
file.read(result.data(), size);
30+
if (!file)
31+
{
32+
result.resize(static_cast<std::size_t>(file.gcount()));
33+
}
34+
2135
return result;
2236
}
2337

@@ -222,7 +236,9 @@ namespace cppwinrt
222236

223237
bool file_equal(std::string const& filename) const
224238
{
225-
if (!std::filesystem::exists(filename) || std::filesystem::file_size(filename) != m_first.size() + m_second.size())
239+
// Non-throwing file_size returns uintmax_t(-1) on errors, which shouldn't ever be the size of m_first or m_second
240+
std::error_code ec;
241+
if (std::filesystem::file_size(filename, ec) != m_first.size() + m_second.size())
226242
{
227243
return false;
228244
}

0 commit comments

Comments
 (0)