简体   繁体   English

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

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

I've been trying to make my program write a string into a binary file using Ofstream::write(), but I could not find out how to (through the interwebs), so I tried writing a struct with a string into the file. 我一直试图让我的程序使用Ofstream :: write()将字符串写入二进制文件,但我无法找到如何(通过interwebs),所以我尝试用字符串写一个结构到文件中。 That worked perfectly; 这非常有效; I could open the file and read the string (with my human eyes), but when I tried to use Ifstream::read() to read the struct, I just got an empty string and the string that I wrote (in this case, "dir" was the empty one, and "fileName" was correctly read). 我可以打开文件并读取字符串(用我的人眼),但是当我尝试使用Ifstream :: read()读取结构时,我只得到一个空字符串和我写的字符串(在这种情况下, “dir”是空的,并且“fileName”被正确读取)。 Any and all help is appreciated :) PS: Both strings are saved in the file... This is my writing code: 任何和所有帮助表示赞赏:) PS:两个字符串都保存在文件中...这是我的编写代码:

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

This is my reading code: 这是我的阅读代码:

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

And this is the "StringStruct" code: 这是“StringStruct”代码:

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

Ok, I recieved some comments (thanks manni66) saying that I have to write as c-strings. 好的,我收到了一些评论(感谢manni66)说我必须写成c-strings。 So I changed my struct to this: 所以我改变了我的结构:

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

So that I was writing each string as a c-string instead. 所以我将每个字符串写成c字符串。

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

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