From 0e781ec76eff10dcc19c472e23ca835da1c47621 Mon Sep 17 00:00:00 2001 From: Nicolas Cornu Date: Fri, 10 May 2024 16:07:31 +0300 Subject: [PATCH] Simplify computation of neuronhome paths (#2874) --- src/modlunit/units.cpp | 61 ++++++++++++++++++------------------------ 1 file changed, 26 insertions(+), 35 deletions(-) diff --git a/src/modlunit/units.cpp b/src/modlunit/units.cpp index 062b8efa20..f8ff9a0d79 100644 --- a/src/modlunit/units.cpp +++ b/src/modlunit/units.cpp @@ -1,4 +1,8 @@ #include <../../nrnconf.h> + +#include +#include + /* /local/src/master/nrn/src/modlunit/units.c,v 1.5 1997/11/24 16:19:13 hines Exp */ /* Mostly from Berkeley */ #include "model.h" @@ -109,28 +113,21 @@ static int Getc(FILE* inp) { #define UNIT_STK_SIZE 20 static struct unit unit_stack[UNIT_STK_SIZE], *usp{nullptr}; -static char* neuronhome() { +static std::string neuronhome() { #if defined(MINGW) - int i; - static char buf[256]; - GetModuleFileName(NULL, buf, 256); - for (i = strlen(buf); i >= 0 && buf[i] != '\\'; --i) { - ; - } - buf[i] = '\0'; // /neuron.exe gone - // printf("setneuronhome |%s|\n", buf); - for (i = strlen(buf); i >= 0 && buf[i] != '\\'; --i) { - ; - } - buf[i] = '\0'; // /bin gone - { - char* u = hoc_dos2unixpath(buf); - strcpy(buf, hoc_dos2unixpath(u)); - free(u); - } + std::string buf(256, '\0'); + GetModuleFileName(nullptr, buf.data(), 256); + // Remove neuron.exe + auto pos = buf.find_last_of('\\'); + buf.resize(pos); + // Remove bin + pos = buf.find_last_of('\\'); + buf.resize(pos); + std::replace(buf.begin(), buf.end(), '\\', '/'); return buf; #else - return getenv("NEURONHOME"); + char* buf = std::getenv("NEURONHOME"); + return (buf != nullptr) ? std::string(buf) : std::string(); #endif } @@ -552,25 +549,19 @@ void unit_init() { } #if defined(__MINGW32__) if (!inpfile) { - s = strdup(neuronhome()); - if (s) { - if (strncmp(s, "/cygdrive/", 10) == 0) { - /* /cygdrive/x/... to c:/... */ - Sprintf(buf, "%c:%s/lib/nrnunits.lib", s[10], s + 11); - } else { - Sprintf(buf, "%s/lib/nrnunits.lib", s); - } - inpfile = fopen(buf, "r"); - free(s); + auto s = neuronhome(); + if (!s.empty()) { + std::string filename = s + "/lib/nrnunits.lib"; + inpfile = fopen(filename.c_str(), "r"); } } #else - if (!inpfile && (inpfile = fopen(dfile, "r")) == (FILE*) 0) { - if ((inpfile = fopen(dfilealt, "r")) == (FILE*) 0) { - s = neuronhome(); - if (s) { - Sprintf(buf, "%s/lib/nrnunits.lib", s); - inpfile = fopen(buf, "r"); + if (!inpfile && (inpfile = fopen(dfile, "r")) == nullptr) { + if ((inpfile = fopen(dfilealt, "r")) == nullptr) { + auto s = neuronhome(); + if (!s.empty()) { + std::string filename = s + "/lib/nrnunits.lib"; + inpfile = fopen(filename.c_str(), "r"); } } }