【问题标题】:How to write members of a class to a binary file using cpp?如何使用 cpp 将类的成员写入二进制文件?
【发布时间】:2013-04-08 06:33:23
【问题描述】:

我正在 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 处引发第一次机会异常(访问冲突读取位置错误)。我是否以错误的方式使用班级成员做错了什么?这是一个独立的项目,而不是任何作业。我已经为此跑了两天了。任何具体的帮助表示赞赏。谢谢。

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

编辑:

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

【问题讨论】:

  • 我们至少要看看XWPuzzle的声明。
  • xWord 对象是在哪里制作的?我想看看你的班级宣言。
  • 抱歉耽搁了。我已经添加了 XWPuzzle 的声明。
  • 除非它们是固定大小的字符串,否则您将获得的乐趣是读回它们。一个简单的处理方法是先写长度,然后是字符串数据,你就会知道要读回多少。
  • 这不就是为什么它们是 NUL 终止的字符串吗?我认为这就是使用 nul 终止字符串的原因。

标签: c++ class binaryfiles data-members


【解决方案1】:

您正在将整数转换为指针并尝试通过该指针写入数据。那是错误的。您应该获取指向校验和的指针,将其转换然后写入

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

与网格和 userGrid 字段相同

【讨论】:

  • 非常感谢!新手错误。
猜你喜欢
  • 2019-05-31
  • 2021-10-18
  • 2012-12-25
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多