added a safe fread variant with error checking.

This commit is contained in:
Axel Kohlmeyer
2019-10-17 09:46:18 -04:00
parent 4e6f83ced2
commit 7d1cd63e1d
2 changed files with 38 additions and 0 deletions

View File

@ -127,6 +127,29 @@ void utils::sfgets(const char *srcname, int srcline, char *s, int size,
return; return;
} }
/* like fread() but aborts with an error or EOF is encountered */
void sfread(const char *srcname, int srcline, void *s, size_t size,
size_t num, FILE *fp, const char *filename, Error *error)
{
size_t rv = fread(s,size,num,fp);
if (rv != num) { // something went wrong
std::string errmsg;
if (feof(fp)) {
errmsg = "Unexpected end of file while reading file '";
} else if (ferror(fp)) {
errmsg = "Unexpected error while reading file '";
} else {
errmsg = "Unexpected short read while reading file '";
}
errmsg += filename;
errmsg += "'";
if (error) error->one(srcname,srcline,errmsg.c_str());
}
return;
}
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
std::string utils::check_packages_for_style(std::string style, std::string utils::check_packages_for_style(std::string style,

View File

@ -69,6 +69,21 @@ namespace LAMMPS_NS {
void sfgets(const char *srcname, int srcline, char *s, int size, void sfgets(const char *srcname, int srcline, char *s, int size,
FILE *fp, const char *filename, Error *error); FILE *fp, const char *filename, Error *error);
/** \brief safe wrapper around fread() which aborts on errors
* or EOF and prints a suitable error message to help debugging
*
* \param srcname name of the calling source file (from FLERR macro)
* \param srcline line in the calling source file (from FLERR macro)
* \param s buffer for storing the result of fread()
* \param size size of data elements read by fread()
* \param num number of data elements read by fread()
* \param fp file pointer used by fread()
* \param filename file name associated with fp (for error message)
* \param error pointer to Error class instance (for abort)
*/
void sfread(const char *srcname, int srcline, void *s, size_t size,
size_t num, FILE *fp, const char *filename, Error *error);
/** \brief Report if a requested style is in a package or may have a typo /** \brief Report if a requested style is in a package or may have a typo
* *
* \param style type of style that is to be checked for * \param style type of style that is to be checked for