代码之家  ›  专栏  ›  技术社区  ›  Davis Last

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

  •  1
  • Davis Last  · 技术社区  · 9 年前

    我一直在尝试让我的程序使用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";
    };
    
    1 回复  |  直到 9 年前
        1
  •  0
  •   Davis Last    9 年前

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

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