【问题标题】:Save Data to a .DAT file将数据保存到 .DAT 文件
【发布时间】:2020-12-02 19:04:49
【问题描述】:

我需要将用户输入的数据保存到 dat 文件中,我得到了商品、价格、数量的描述 我的代码是这样的,但它不保存数据

void saveInventory()
{
ofstream outfile;
outfile.open("inventory.dat", ios::binary);
if(!outfile.is_open()){
    cout<<"File openning error."<<endl;
    return;
}
outfile.write((char*)&items, sizeof(items));
outfile.close();
}

【问题讨论】:

  • 带有参数和类型的纯函数可以让您更轻松地查看您实际尝试保存的内容。
  • 还在等待有经验的用户
  • 关于序列化和反序列化(保存和加载的一般情况):C++ FAQ 有一个完整的方面:Serialization and Unserialization,我可以热情地推荐它作为开始。
  • 不幸的是,您没有公开items 的定义方式。 (因此,对minimal reproducible example 的请求。)假设items 被定义为std::vector&lt;Item&gt; items;,那么您的写入将不会达到您的预期。 std::vector 是一个包装器,其中内容存储在堆上并在内部进行管理/指向。因此,您的write() 将只写入此指针,而不考虑您打算写入的实际内容。 (更好?);-)

标签: c++


【解决方案1】:

你可能需要写这样的东西:

    outfile.write((char*)&items[0], items.size() * sizeof(item));

【讨论】:

  • 在不知道items 是如何声明的情况下,如何知道这是否合法甚至编译?
  • 假设 items 是一个向量,如:outfile.write((char*)&items, sizeof(items));不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多