c++ - 如何使用cpp将类的成员写入二进制文件?

标签 c++ class binaryfiles data-members

我正在用 cpp 编写一个小型后端,我必须在其中将一些填字游戏数据写入二进制文件。我创建了一个 XWPuzzle 类,其所有数据成员都是公开的,xWord 是此类的一个对象。这是我试图写入二进制文件的代码片段:

#include"binIncludes.h"

int main(int argc, char** argv)
{
    cout<<"Bin read-write Tester\n";
    xWord.title="Yeah!\0";
    xWord.author="Nobody\0";
    xWord.grid=147;
    xWord.userGrid=109;
    xWord.clues[0]="as\0";
    xWord.clues[1]="de\0";
    xWord.clues[2]="re\0";
    xWord.solution[0]="ASSET\0";
    xWord.solution[1]="DEER\0";
    xWord.solution[2]="REED\0";
    xWord.checksum=(int)(xWord.title.at(0))+(int)(xWord.author.at(0))+xWord.grid+xWord.userGrid;
    xWord.checksum+=(int)(xWord.clues[0].at(0))+(int)(xWord.clues[1].at(0))+(int)(xWord.clues[2].at(0));
    xWord.checksum+=(int)(xWord.solution[0].at(0))+(int)(xWord.solution[1].at(0))+(int)(xWord.solution[2].at(0));
    fstream file;
    file.open("binTest.bin",ios::out|ios::binary);
    file.write(SIGNATURE,sizeof(SIGNATURE));
    file.write(VERSION,sizeof(VERSION));
    file.write(TYPE,sizeof(TYPE));
    file.write((char*)xWord.checksum,sizeof(xWord.checksum));
    file.write(xWord.title.c_str(),xWord.title.size());
    file.write(xWord.author.c_str(),xWord.author.size());
    file.write((char*)xWord.grid,sizeof(xWord.grid));
    file.write((char*)xWord.userGrid,sizeof(xWord.userGrid));
    file.close();
    cout<<"File written\n";
    _getch();
    return 0;
}

SIGNATURE, VERSION 和 TYPE 都是以null结尾的字符串,但是编译后的程序到了该行就报错了

file.write((char*)xWord.checksum,sizeof(xWord.checksum));

调试器在 MSVCR100.dll 中抛出第一次异常(访问冲突读取位置错误)。我是否以错误的方式使用类(class)成员做错了什么?这是一个独立的项目,没有任何作业。我已经为此奔波了两天了。任何具体的帮助表示赞赏。谢谢。

除了这个类的数据,我还有其他数据要写入。

编辑:

XWPuzzle.h:

#ifndef XWPULZZLE_H
#define XWPUZZLE_H

#include"binIncludes.h"

class XWPuzzle
{
    public:
        string title;
        string author;
        int grid;
        int userGrid;
        string clues[3];
        string solution[3];
        int checksum;
} xWord;

#endif

binDefines.h:

#ifndef BIN_DEFINES_H
#define BIN_DEFINES_H

#include"binIncludes.h"

#define SIGNATURE "BinFile\0"
#define VERSION "0.1.1\0"
#define TYPE "With Solution\0"

#endif

binIncludes.h:

#ifndef BIN_INCLUDES_H
#define BIN_INCLUDES_H

#include<iostream>
#include<conio.h>
#include<string>
#include<fstream>

using namespace std;

#include"binDefines.h"
#include"XWPuzzle.h"

#endif

最佳答案

您正在将整数转换为指针并尝试通过该指针写入数据。那是错误的。你应该得到一个校验和的指针,转换它然后写

file.write((char*)(&xWord.checksum),sizeof(xWord.checksum));

与 grid 和 userGrid 字段相同

关于c++ - 如何使用cpp将类的成员写入二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15872700/

相关文章:

c++ - 无序自定义对象集的 boost 池

c++ - 将所有 nsdata 字节复制到 char* 错误中

c++ - 有没有什么方法可以在没有 std::move 的情况下调用 C++ 中的移动赋值运算符?

python - 将多个 numpy 数组流式传输到一个文件

c - 在C语言中查看二进制文件时,我按位还是按字节查看?

c++ - 使用 C/C++ DLL header 构建构建 C 应用程序时出现语法错误 C2059

ios - swift 类 'nil' 中的所有值

javascript - 使用悬停功能,Jquery 在随机位置生成 div

模板化类对象的 C++ vector

C++ 将 bitset 写入二进制文件