【问题标题】:How to prevent a struct member value from being overwritten when updating a file c++更新文件c ++时如何防止结构成员值被覆盖
【发布时间】:2012-12-30 21:13:34
【问题描述】:

假设我有一个二进制文件、一个文本文件和 3 个结构成员。我已经为结构成员 1 写了一组数字,我们称之为“score1”。现在,我想用 struct member 2“score final”更新二进制文件。

这个分数最终将例如计算 score1 的百分比并将其写入二进制文件。现在我们将写入 score2 的第二组值。当我这样做时,score1 值以及二进制文件中的原始分数最终值都消失了,现在我只有分数 2 和从 score2 计算的新分数最终值。

我的代码示例:

struct Scores{
float score1;
float score2;
float final;
};

fstream afile;
fstream afile2;

//afile will read in sets of score1 values from text file

//afile2 will output sets of score1 values to binary file
//while final is also outputted.

//Then, afile will again read in sets different of score2 values from text file
//afile 2 will output sets of score1 values to binary file 
//and final is also outputted but with new calculations

正在读取的文本文件将如下所示;

12.2
41.2
51.5
56.2
9.2

and the second text file:
76.1
5.7
62.3
52.7
2.2

我会将结构 score1 和 score2 和 final 输出到一个看起来像这样的文本文件

Final   Score1   Score2 
       12.2      76.1
       41.2      5.7
       51.5      62.3
       56.2      52.7
       9.2       2.2 

最后一栏是空的,但你明白我的意思。

现在的问题:

  1. 每次我将它输出到文本文件时,我只能执行最后一列 score1 或最后一列 score2。但不是 score1, score2,final。

  2. 我希望能够将 score1 的最终结果相加并与 score2 的最终结果相加并输出两个相加 决赛。

现在这是一项任务,我有一些限制,我必须完成的任务 贴近。

规则:从文本文件中读取 score1 和 score2。使用二进制存储 score1, score2, 决赛。使用这三个写入单个文本文件 列。

【问题讨论】:

  • 那么内存中不允许同时有 score1 和 score2 吗?
  • 我是,就是不知道怎么用写代码。到目前为止,我没有尝试过任何工作。

标签: c++ struct binary overwrite records


【解决方案1】:

如果您的二进制文件是一个简单的结构分数对象列表,您可以实现两个非常简单的函数来修改二进制文件(不检查错误,如果它编译等 - 自己做)。

Scores readScores(std::ifstream& file, unsigned int scoresNum)
{
    Scores scores;
    file.seekg(scoresNum*sizeof(Scores), std::ios_base::beg);
    file.read(static_cast<char*>(&scores),sizeof(Scores));
    return scores;
}

void writeScores(std::ofstream& file, unsigned int scoresNum, const Scores& scores)
{
    file.seekp(scoresNum*sizeof(Scores), std::ios_base::beg);
    file.write(static_cast<char*>(&scores),sizeof(Scores));
}

您加载第一个文本文件,修改二进制文件。然后是第二个文件,再次修改并根据二进制文件的最终状态生成结果。希望能帮到你解决问题。

【讨论】:

  • 这类似于我的代码。如果我在写之前使用 seekp,我在最终文本文件中的所有值将只显示我从文本文件中获取的最后一个值。
【解决方案2】:

这是不可能的。 IO 流类允许您将数据附加到现有文件或截断它并从头开始重写。

在你的情况下,追加是行不通的。所以你剩下的就是截断并重写文件中你想要的所有信息。

【讨论】:

  • 有没有办法不顾我的限制来做这件事。是的,我的意图是在我输入 score1 和 score2 后重写结构成员的输出文本文件。我不确定这是否是您的意思。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
  • 2021-02-08
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
  • 2015-09-09
相关资源
最近更新 更多