繁体   English   中英

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

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

我一直试图让我的程序使用Ofstream :: write()将字符串写入二进制文件,但我无法找到如何(通过interwebs),所以我尝试用字符串写一个结构到文件中。 这非常有效; 我可以打开文件并读取字符串(用我的人眼),但是当我尝试使用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-strings。 所以我改变了我的结构:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM