无法使用 fstream 更新文本文件中的文本

Cannot update the text in text file using fstream

本文关键字:文本 文件 更新 fstream      更新时间:2023-10-16

我正在尝试减小存储在文本文件中的数字的值,如下所示:

fstream countfile;
countfile.open("adminsongcount.txt");
countfile >> songcount;
songcount--;
countfile << songcount;
countfile.close();

显然,计数应该减少 1,比如从 4 减少到 3,但事实并非如此。在打开 adminsongcount 时.txt我仍然得到 4 的值。我在这里错过了什么?

如果adminsongcount.txt最初由单个字符组成'4',运行此代码后它将有两个字符:'4'后跟'3'。如果您重复相同的读取,您将再次获得'4'

要解决此问题,代码应在写入之前查找文件的开头:

countfile.seekp(0);

这会将放置指针(因此名称末尾的"p"(设置为文件的开头。