那么...有没有办法阻止文件自动清除? (c++)
So...is there a way to stop files from clearing automatically? (c++)
所以我正在制作一个非常简单的猜谜主机游戏,我想将数据永久存储在一个文件中(高分)。但是,每次我编译文件时,我都使用空文件本身。无论如何要阻止它吗?
我已经尝试了很多没有用的东西,老实说我不知道问题出在哪里。我猜它与 fin 和 fout 有关,但对于其他人来说它似乎有效
#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();
}
不要使用两个流并行打开文件两次。此外,简单的 open-for-writing 不会截断您的文件,但会将您置于文件的开头,因此您将覆盖现有数据;参见 。您必须使用写入模式打开文件。
您需要:
- 打开您的文件进行输入和输出 - 并且不截断它;请参阅:
What does it mean to open an output file as both input and output? 或
- 仅在您的应用程序启动时打开您的文件进行读取,打开它进行写入,并在它存在时写入它(或每隔 once-in-a-while 以获得更好的弹性)。
所以我正在制作一个非常简单的猜谜主机游戏,我想将数据永久存储在一个文件中(高分)。但是,每次我编译文件时,我都使用空文件本身。无论如何要阻止它吗? 我已经尝试了很多没有用的东西,老实说我不知道问题出在哪里。我猜它与 fin 和 fout 有关,但对于其他人来说它似乎有效
#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();
}
不要使用两个流并行打开文件两次。此外,简单的 open-for-writing 不会截断您的文件,但会将您置于文件的开头,因此您将覆盖现有数据;参见
您需要:
- 打开您的文件进行输入和输出 - 并且不截断它;请参阅:
What does it mean to open an output file as both input and output? 或 - 仅在您的应用程序启动时打开您的文件进行读取,打开它进行写入,并在它存在时写入它(或每隔 once-in-a-while 以获得更好的弹性)。