【问题标题】:Adding to a file without erasing what is inside添加到文件而不删除里面的内容
【发布时间】:2019-06-27 04:17:53
【问题描述】:

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

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++


【解决方案1】:

假设 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;
}

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

在你的情况下,你必须以这种方式改变它:

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

【讨论】:

    【解决方案2】:

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

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

    将模式设置为追加,假设您使用的是fstream::open()

    【讨论】:

      猜你喜欢
      • 2013-04-28
      • 2013-04-17
      • 2010-12-10
      • 1970-01-01
      • 2018-11-12
      • 2021-12-13
      • 1970-01-01
      • 2020-03-22
      • 2012-04-08
      相关资源
      最近更新 更多