2017-07-06 145 views
-3
#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。C++如何覆盖C++中的文本文件中的数据?

里面的data.txt它读取1016,这是不准确的!

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

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

谢谢。

+0

请参考[tour](https://stackoverflow.com/tour)并阅读[help](https://stackoverflow.com/help)页面。 – Ron

回答

2

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