【问题标题】:C++ How to overwrite data in text file in c++?C++ 如何在 C++ 中覆盖文本文件中的数据?
【发布时间】:2017-12-11 01:09:49
【问题描述】:
#include<iostream>
#include<fstream>
using namespace std;
string dataFile = "data.txt";
int counter;

int main()
{
    string input ="";
    fstream data;
    data.open(dataFile, ios::app | ios::out | ios::in );
    getline(data, input);
    if (input == "")//The file must be new
    {
        counter = 0;
    }else {
        counter = stoi(input);
    }

    /*
        Program does some stuff that increases the counter
        Right before program ends we update the file
    */
    data.clear();
    data << counter;
    data.close();
    return 0;
}

所以这只是一些示例代码。第一次运行程序时,计数器从 0 开始,这是准确的。假设你在这场比赛中得到 10 分。游戏结束时你的计数器为 10,保存到文件中没问题。所以让我们重新打开应用程序,你会看到计数器是 10,很酷,这次你获得了 6 分。所以在游戏中,计数器读取 16。在应用程序关闭之前,16 被写入 data.txt。

data.txt里面是1016,不准确!

如何在将准确的计数器信息写入文件之前清除 data.txt 中的文本?

我在其他地方读到您无法使用 fstream 清除文件的内容,是否有更有效的方法来覆盖文件中的数据?

谢谢。

【问题讨论】:

标签: c++ fstream overwrite


【解决方案1】:

将文件读入内存。更新值。重写文件。

【讨论】:

    猜你喜欢
    • 2015-09-20
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 2012-05-11
    相关资源
    最近更新 更多