C++ 添加到文件而不删除其中的内容

C++ 添加到文件而不删除其中的内容,c++,C++,我正在编写一个代码,从用户那里获取一些输入并将其存储在一个文件中。我的代码应该保留旧数据并添加新数据,但每次运行代码时,文件中的旧数据都会被新数据替换 if(input == 1){ outFile.open("personnel2.dat"); int numRecords = 0; do{ cout << "#1 of 7 - Enter Employee Worker

我正在编写一个代码,从用户那里获取一些输入并将其存储在一个文件中。我的代码应该保留旧数据并添加新数据,但每次运行代码时,文件中的旧数据都会被新数据替换

if(input == 1){
             outFile.open("personnel2.dat");
             int numRecords = 0;
             do{
                 cout << "#1 of 7 - Enter Employee Worker ID Code(i.e AF123): ";
                 cin >> id;
                 cout << "#2 of 7 - Enter Employee LAST Name: ";
                 cin >> lastN;
                 cout << "#3 of 7 - Enter Employee FIRST Name: ";
                 cin >> firstN;
                 cout << "#4 of 7 - Enter Employee Work Hours: ";
                 cin >> workH;
                 cout << "#5 of 7 - Enter Employee Pay Rate: ";
                 cin >> payRate;
                 cout << "#6 of 7 - Enter FEDERAL Tax Rate: ";
                 cin >> federalTax;
                 cout << "#7 of 7 - Enter STATE Tax Rate: ";
                 cin >> stateTax;
                 outFile << id << " " << lastN << " " << firstN << " " << workH << " " << payRate << " "
                         << federalTax << " " << stateTax << "\n";
                 numRecords++;
                 cout << "Enter ANOTHER Personnel records? (Y/N): ";
                 cin >> moreRecords;
             }while(moreRecords != 'N' && moreRecords != 'n');

             outFile.close();
             cout << numRecords << " records written to the data file.\n";

             }
if(输入==1){
出口打开(“人员数据”);
int numRecords=0;
做{
cout>id;
最后;
首先;
工作;
支付率;
联邦税;
国家税收;
outFileChange
outFile.open(“personnel2.dat”);

outFile.open(“personel2.dat”,std::fstream::app);

若要将模式设置为“附加”,请假定您使用的是
fstream::open()
更改
outFile.open(“personel2.dat”);

outFile.open(“personel2.dat”,std::fstream::app);


要设置附加模式,假设您使用的是
fstream::open()

假设outfile是
std::oftream
的实例,其背后的原因是使用
open()时
函数在stream
对象的
上,文件以ios_base::out模式打开,该模式强制在插入新内容之前删除以前的内容

为了附加数据,必须明确指定
append
模式

例如:

#include <fstream>      // std::ofstream

int main () {

  std::ofstream ofs;
  ofs.open ("test.txt", std::ofstream::out | std::ofstream::app);

  ofs << " more lorem ipsum";

  ofs.close();

  return 0;
}

假设outfile是
std::ofstream
的实例,其背后的原因是当您在
ofstream
对象上使用
open()
函数时,该文件将以ios_base::out模式打开,该模式强制在插入新内容之前删除以前的内容

为了附加数据,必须明确指定
append
模式

例如:

#include <fstream>      // std::ofstream

int main () {

  std::ofstream ofs;
  ofs.open ("test.txt", std::ofstream::out | std::ofstream::app);

  ofs << " more lorem ipsum";

  ofs.close();

  return 0;
}
可能的重复可能的重复