Fstream 没有从二进制数据中读取完整的结构 (C++)

Fstream not reading a complete struct from binary data (C++)

我一直试图让我的程序使用 Ofstream::write() 将字符串写入二进制文件,但我无法找到如何(通过互联网),所以我尝试编写一个结构将字符串放入文件中。效果很好;我可以打开文件并读取字符串(用我的眼睛),但是当我尝试使用 Ifstream::read() 读取结构时,我只得到一个空字符串和我写的字符串(在这种情况下, "dir" 是空的, "fileName" 被正确读取)。 任何帮助表示赞赏:) PS: 两个字符串都保存在文件中... 这是我写的代码:

StringStruct texPath;
texPath.dir = "src/Assets/";
texPath.fileName = "bricks_top.png";
file.write((char*)&texPath, sizeof(texPath));

这是我的阅读代码:

StringStruct texFile;
file.read((char*)&texFile, sizeof(texFile));
std::string filepath = "";
filepath += texFile.dir;
filepath += texFile.fileName;
std::cout << filepath;

这是 "StringStruct" 代码:

struct StringStruct {
    std::string dir = "src/Assets/";
    std::string fileName = "Example.png";
};

好的,我收到了一些评论(感谢 manni66)说我必须写成 C 字符串。所以我将结构更改为:

struct StringStruct {
    char* dir = "src/Assets/";
    char* fileName = "Example.png";
};

所以我将每个字符串写成 C 字符串。