Skip to content

Commit

Permalink
Merge pull request #1 from LBNL-ETA/openFileHelperRewrite
Browse files Browse the repository at this point in the history
Added new implementation of openFileHelper that uses safe versions of…
  • Loading branch information
StephenCzarnecki authored Jul 18, 2024
2 parents 835838a + f2f955b commit c65d032
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/xmlParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@
****************************************************************************
*/

#include <sstream>
#include <exception>
// Component produces warning messages that were disabled only for this file.
#pragma warning(disable : 4706)
#pragma warning(disable : 4100)
Expand Down Expand Up @@ -745,6 +747,51 @@ namespace XMLParser
return xnode;
}

XMLNode XMLNode::openFileHelperThrows(XMLCSTR filename, XMLCSTR tag)
{
// guess the value of the global parameter "characterEncoding"
// (the guess is based on the first 200 bytes of the file).
FILE * f;
errno_t err;
err = fopen_s(&f, filename, "rb");
if(err)
{
char buff[2000];
strerror_s(buff, err);
throw std::runtime_error(buff);
}
if(f)
{
char bb[205];
int l = (int)fread(bb, 1, 200, f);
XMLNode::setGlobalOptions(
XMLNode::guessCharEncoding(bb, l), 1, 1, 1);
fclose(f);
}

// parse the file
XMLResults results;
XMLNode node = XMLNode::parseFile(filename, tag, &results);

// display error message (if any)
if(results.error != eXMLErrorNone)
{
std::stringstream msg;

msg << "XML Parsing error in file: " << filename << " "
<< XMLNode::getError(results.error) << " in line: " << results.nLine
<< ", column: " << results.nColumn;

if(results.error == eXMLErrorFirstTagNotFound)
{
msg << " First Tag should be " << tag;
}

throw std::runtime_error(msg.str());
}
return node;
}

/////////////////////////////////////////////////////////////////////////
// Here start the core implementation of the XMLParser library //
/////////////////////////////////////////////////////////////////////////
Expand Down
2 changes: 2 additions & 0 deletions src/xmlParser.h
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,8 @@ namespace XMLParser {
* @param tag the name of the first tag inside the XML file. If the tag parameter is omitted, this function returns a node that represents the head of the xml document including the declaration term (<? ... ?>).
*/

static XMLNode openFileHelperThrows(XMLCSTR filename, XMLCSTR tag = NULL);

static XMLCSTR getError(XMLError error); ///< this gives you a user-friendly explanation of the parsing error

/// Create an XML string starting from the current XMLNode.
Expand Down

0 comments on commit c65d032

Please sign in to comment.