写入文件时避免覆盖现有文件的内容
我正在尝试制作一款将高分实现到 .txt 文件中的游戏。我的问题是:当我做出这样的声明时:
ofstream fout("filename.txt");
这会创建一个具有该名称的文件,还是只是查找一个具有该名称的文件?
问题是,每当我重新启动程序并做出以下声明:
fout << score << endl << player;
它会覆盖我以前的分数!
有什么办法可以让我在写入文件时新分数不会覆盖旧分数?
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:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
std::ofstream
默认创建一个新文件。您必须使用 append 参数 创建文件。std::ofstream
creates a new file by default. You have to create the file with the append parameter.如果您只想追加到文件末尾,则可以以追加模式打开文件,因此任何写入都在文件末尾完成,并且不会覆盖先前存在的文件内容:
如果您想用数据覆盖特定的文本行,而不是仅仅使用附加模式将它们附加到末尾,您可能最好读取文件并解析数据,然后修复它(添加任何内容,删除任何内容,编辑任何内容)并写入一切都重新回到文件中。
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:
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.