小编Hen*_*yer的帖子

从函数返回后字符串似乎被释放

我目前正在尝试创建一个简单的函数来读取文件的内容并将其存储到 astd::stringchar数组中。我遇到了这样的问题:数据在函数内完全读取,但在调用函数时似乎被删除/释放。

\n

我已将这个问题隔离到一个小程序中:

\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)

c++ fstream lifetime ifstream

3
推荐指数
1
解决办法
102
查看次数

标签 统计

c++ ×1

fstream ×1

ifstream ×1

lifetime ×1