我目前正在尝试创建一个简单的函数来读取文件的内容并将其存储到 astd::string或char数组中。我遇到了这样的问题:数据在函数内完全读取,但在调用函数时似乎被删除/释放。
我已将这个问题隔离到一个小程序中:
\n入口.cpp
\n#include <string>\n#include <fstream>\n#include <iostream>\n\nconst char* ReadFile(const std::string& path) {\n\n std::ifstream file;\n\n try {\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n file.open(path);\n\n if (!file.is_open()) {\n throw;\n }\n }\n catch (std::exception e) { //file does not exist\n std::string errmsg = "Unable to open file at path: " + path;\n\n std::cout << errmsg << std::endl;\n\n throw new std::exception(errmsg.c_str());\n }\n\n\n std::string contents;\n try {\n contents = std::string{ std::istreambuf_iterator<char>{file}, {} };\n }\n catch (const std::ifstream::failure& e) {\n\n std::cout …Run Code Online (Sandbox Code Playgroud)