From ced0d350f00c3f0647ec9dd79ec16a9eb21d62ca Mon Sep 17 00:00:00 2001 From: Axel Kohlmeyer Date: Sat, 14 Jun 2025 09:02:00 -0400 Subject: [PATCH] handling parsing exceptions and check for error creating a backup --- tools/json/reformat-json.cpp | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/tools/json/reformat-json.cpp b/tools/json/reformat-json.cpp index 54897233b4..abe0b9dbb3 100644 --- a/tools/json/reformat-json.cpp +++ b/tools/json/reformat-json.cpp @@ -4,6 +4,7 @@ #include #include #include +#include using json = LAMMPS_NS::json; @@ -28,20 +29,28 @@ int main(int argc, char **argv) return 2; } - auto jsondata = json::parse(fp, nullptr, true, true); - fclose(fp); + try { + auto jsondata = json::parse(fp, nullptr, true, true); + fclose(fp); + if (rename(file.c_str(), backup.c_str())) { + printf("Cannot create backup for file %s: %s\n", file.c_str(), strerror(errno)); + return 3; + } - rename(file.c_str(), backup.c_str()); - - fp = fopen(file.c_str(), "w"); - if (!fp) { - printf("Cannot open file %s for writing: %s\n", file.c_str(), strerror(errno)); - return 3; + fp = fopen(file.c_str(), "w"); + if (!fp) { + printf("Cannot open file %s for writing: %s\n", file.c_str(), strerror(errno)); + return 4; + } + std::string data = jsondata.dump(indent); + data += '\n'; + fputs(data.c_str(), fp); + fclose(fp); + } catch (std::exception &e) { + printf("%s: %s\nSkipping file...\n", argv[i], e.what()); + fclose(fp); } - std::string data = jsondata.dump(indent); - data += '\n'; - fputs(data.c_str(), fp); - fclose(fp); + } return 0; }