diff --git a/source/api_c/include/c_api.h b/source/api_c/include/c_api.h index d36bd2206d..8ddf5dca9f 100644 --- a/source/api_c/include/c_api.h +++ b/source/api_c/include/c_api.h @@ -1007,6 +1007,13 @@ extern void DP_ConvertPbtxtToPb(const char* c_pbtxt, const char* c_pb); */ extern void DP_PrintSummary(const char* c_pre); +/** + * @brief Read a file to a char array. + * @param[in] c_model The name of the file. + * @return const char* The char array. + */ +const char* DP_ReadFileToChar(const char* c_model); + #ifdef __cplusplus } /* end extern "C" */ #endif diff --git a/source/api_c/include/deepmd.hpp b/source/api_c/include/deepmd.hpp index cf7285fb41..4cd4cf79e6 100644 --- a/source/api_c/include/deepmd.hpp +++ b/source/api_c/include/deepmd.hpp @@ -1575,5 +1575,16 @@ class DipoleChargeModifier { DP_DipoleChargeModifier *dcm; int nsel_types; }; + +/** + * @brief Read model file to a string. + * @param[in] model Path to the model. + * @param[out] file_content Content of the model file. + **/ +void inline read_file_to_string(std::string model, std::string &file_content) { + const char *c_file_content = DP_ReadFileToChar(model.c_str()); + file_content = std::string(c_file_content); +}; + } // namespace hpp } // namespace deepmd diff --git a/source/api_c/src/c_api.cc b/source/api_c/src/c_api.cc index ffe860545c..979ebfe82a 100644 --- a/source/api_c/src/c_api.cc +++ b/source/api_c/src/c_api.cc @@ -1134,4 +1134,11 @@ void DP_PrintSummary(const char* c_pre) { deepmd::print_summary(pre); } +const char* DP_ReadFileToChar(const char* c_model) { + std::string model(c_model); + std::string file_content; + deepmd::read_file_to_string(model, file_content); + return string_to_char(file_content); +} + } // extern "C" diff --git a/source/api_c/tests/test_read_file_to_string.cc b/source/api_c/tests/test_read_file_to_string.cc new file mode 100644 index 0000000000..fb27ad8b1d --- /dev/null +++ b/source/api_c/tests/test_read_file_to_string.cc @@ -0,0 +1,25 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "deepmd.hpp" +TEST(TestReadFileToString, readfiletostring) { + std::string file_content; + deepmd::hpp::read_file_to_string("../../tests/infer/deeppot.txt", + file_content); + + std::string file_name_2 = "../../tests/infer/deeppot.txt"; + std::stringstream buffer; + std::ifstream file_txt(file_name_2); + buffer << file_txt.rdbuf(); + std::string expected_out_string = buffer.str(); + EXPECT_STREQ(expected_out_string.c_str(), file_content.c_str()); +}