C++ 避免在写入文件时覆盖现有文件的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8220196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:12:07  来源:igfitidea点击:

Avoid contents of an existing file to be overwritten when writing to a file

c++ofstream

提问by Monkeyanator

I am trying to make a game that implements high scores into a .txt file. The question I have is this : when I make a statement such as:

我正在尝试制作一个将高分放入 .txt 文件的游戏。我的问题是:当我发表以下声明时:

ofstream fout("filename.txt");

Does this create a file with that name, or just look for a file with that name?

这会创建一个具有该名称的文件,还是仅查找具有该名称的文件?

The thing is that whenever I start the program anew and make the following statement:

问题是,每当我重新启动程序并做出以下声明时:

fout << score << endl << player; 

it overwrites my previous scores!

它覆盖了我以前的分数!

Is there any way for me to make it so that the new scores don't overwrite the old ones when I write to the file?

有什么办法可以让我在写入文件时新的分数不会覆盖旧的分数?

回答by J. Calleja

std::ofstreamcreates a new file by default. You have to create the file with the append parameter.

std::ofstream默认情况下创建一个新文件。您必须使用append 参数创建文件。

ofstream fout("filename.txt", ios::app); 

回答by Seth Carnegie

If you simply want to append to the end of the file, you can open the file in append mode, so any writing is done at the end of the file and does not overwrite the contents of the file that previously existed:

如果您只是想追加到文件的末尾,您可以以追加模式打开文件,因此任何写入都在文件末尾完成,并且不会覆盖先前存在的文件内容:

ofstream fout("filename.txt", ios::app);

If you want to overwrite a specific line of text with data instead of just tacking them onto the end with append mode, you're probably better off reading the file and parsing the data, then fixing it up (adding whatever, removing whatever, editing whatever) and writing it all back out to the file anew.

如果您想用数据覆盖特定的文本行,而不是仅使用附加模式将它们添加到末尾,那么您最好阅读文件并解析数据,然后修复它(添加任何内容,删除任何内容,编辑无论如何)并将其全部重新写入文件。