【问题标题】:So...is there a way to stop files from clearing automatically? (c++)那么......有没有办法阻止文件自动清除? (c++)
【发布时间】:2021-01-18 13:03:53
【问题描述】:

所以我正在制作一个非常简单的猜谜游戏机,我想将数据永久存储在一个文件中(高分)。但是每次我编译我正在使用的文件时都会清空自己。有没有办法阻止它? 我尝试了很多没有用的东西,老实说,我不知道问题出在哪里。我猜这与鳍和鳍有关,但对其他人来说似乎有效

#include <iostream>
#include <fstream>
#include <time.h>
#include <conio.h>

int hs;

//this would be the play_game() function, unrelated to the subject

int main()
{
    std::ofstream fout;
    fout.open("HS.txt");

    std::ifstream fin;
    fin.open("HS.txt");

    srand(time(NULL));

    //menu with 4 options, play, quit, help and highscore (which i'm working on)

    fin.close();
    fout.close();
}


   

【问题讨论】:

  • 检查std::fstream::open()mode参数和std::ios::app具体。
  • @πάνταῥεῖ:这个问题不是重复的,因为 OP 不只是想要追加,他们想要读取和写入。
  • 如 panta rei 所说,将您的 fout.open 命令修改为 fout.open ("HS.txt", std::ofstream::out | std::ofstream::app);
  • @Menelaus 要处理同一个文件资源的读取和写入,只需使用一个std::fstream,否则您需要同步您的foutfin通过使用相同的rdbuf() 指针。

标签: c++ fstream iostream


【解决方案1】:

不要使用两个流同时打开文件两次。此外,简单的 open-for-writing 不会截断您的文件,但会将您置于文件的开头,因此您将覆盖现有数据;见this question。您必须使用写入模式打开文件。

您需要:

  1. 为输入和输出打开您的文件 - 并且不截断它;请参阅:
    What does it mean to open an output file as both input and output?,或
  2. 仅在应用启动时打开文件进行读取,打开文件进行写入,并在文件存在时写入(或每隔一段时间写入一次以提高弹性)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2013-06-23
    • 1970-01-01
    • 2021-11-17
    • 2018-08-20
    • 1970-01-01
    相关资源
    最近更新 更多