From 8f9f4d461d536083a6f8459b9cb5d8a8586b7513 Mon Sep 17 00:00:00 2001 From: Love Billenius Date: Wed, 4 Sep 2024 22:14:31 +0200 Subject: [PATCH] Improve fileRead --- src/life.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/life.cpp b/src/life.cpp index 8386583..3bfebd9 100755 --- a/src/life.cpp +++ b/src/life.cpp @@ -39,7 +39,7 @@ std::string input(const char *message) { bool fileExists(const char *fileName) { return access(fileName, 0) == 0; } -std::string fileRead(const char *filePath) { +std::string fileRead(const std::string &filePath) { std::ifstream file(filePath, std::ios::binary); if (!file.is_open()) throw std::runtime_error("File couldn't be found"); @@ -51,7 +51,10 @@ std::string fileRead(const char *filePath) { content.append(buf, file.gcount()); content.append(buf, file.gcount()); - file.close(); + if (!file.eof() && file.fail()) + throw std::runtime_error("Error: Failed to read the file '" + filePath + + "'"); + return content; } @@ -167,7 +170,7 @@ int main() { } std::string fileContents; try { - fileContents = fileRead(inputFile.c_str()); + fileContents = fileRead(inputFile); } catch (std::exception &e) { std::cerr << "Failed to read file: " << e.what() << std::endl; return 1;