当我关闭程序并在c++中再次运行时,如何阻止我的记录被覆盖

How can I stop my records from overwriting when i close the program and run it again in c++

本文关键字:何阻止 我的 记录 覆盖 运行时 关闭程序 c++      更新时间:2023-10-16

我试图将一些用户输入保存到dat文件中,当程序关闭并再次打开时,我想将新记录保存到我已经得到的记录上。。我不确定最新的命令是什么来读取数据并在屏幕上显示我读过书,但它们都有旧的命令,但不起作用。

//account.h
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <String>
#define _CRT_SECURE_NO_DEPRECATE
#include <fstream>
#include <stdlib.h>
using namespace std; 
struct Account
{
public :
void login();
void userRegister();
protected :
int username;
int password;
};

void Account :: userRegister()
{
Account myAccount;
char terminator;
int myUserID = 0;
int myPassword = 0;
 std::cout << "Enter Your 8 digit UserID";
cin >>myUserID  ;
        cout << "Enter Your 6 digit password";
cin >> myPassword ;
FILE * dat = fopen("Accounts.dat", "wb");
myAccount.userID ;
myAccount.password ;
fwrite(&myAccount, sizeof(myAccount), 1, dat);
        //cin.get (terminator);
        fclose (dat);

  }

以追加模式打开文件。

这里a告诉附加,如果文件不存在,则+创建文件。

FILE * dat = fopen("Accounts.dat", "ab+");

http://www.cplusplus.com/reference/cstdio/fopen/

您似乎在询问如何将新数据添加到现有文件中。要做到这一点,您需要在附加模式下打开文件。

更改

FILE * dat = fopen("Accounts.dat", "wb");

FILE * dat = fopen("Accounts.dat", "ba+");