添加到文件而不删除内部内容

时间:2019-02-03 00:48:22

标签: c++

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

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";

             }

2 个答案:

答案 0 :(得分:3)

更改outFile.open("personnel2.dat");

outFile.open("personnel2.dat", std::fstream::app);

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

答案 1 :(得分:1)

假设outfile是std::ofstream的实例,其背后的原因是,当您在open()对象上使用ofstream函数时,该文件以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;
}

来源:http://www.cplusplus.com/reference/fstream/ofstream/open/

在您的情况下,您必须以这种方式进行更改:

outFile.open("personnel2.dat", std::ofstream::out | std::ofstream::app);