添加到文件而不删除里面是什么

问题描述 投票:1回答:2

我写这需要一些来自用户的输入,将其存储在一个文件中的代码。我的代码应该保持旧数据,并添加新的数据,但我每次运行该代码的旧数据,这是文件中的时间被用新的更换。

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

             }
c++
2个回答
1
投票

假设OUTFILE是std::ofstream的情况下,背后的原因是,当您使用open()功能ofstream对象上,该文件中强制插入新的人之前清除原有内容的ios_base ::输出模式打开。

为了追加数据,你必须明确地指定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);

3
投票

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

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

设置模式追加,假设你使用fstream::open()

热门问题
推荐问题
最新问题