1

I am writing a code that takes some input from the user and stores it in a file. My code is supposed to keep the old data and add the new data, but every time I run the code the old data that was in the file gets replaced by the new one.

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

             }
  • Possible duplicate of [C++ fstream overwrite instead of append](https://stackoverflow.com/questions/15056406/c-fstream-overwrite-instead-of-append) – Martin Heralecký Feb 03 '19 at 00:51

2 Answers2

3

Change outFile.open("personnel2.dat");

to

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

to set the mode to append, assuming you are using fstream::open().

PsychoMantis
  • 993
  • 2
  • 13
  • 29
1

Assuming that outfile is instance of std::ofstream, The reason behind that is that when you use open() function on ofstream object, the file is opened in ios_base::out mode which enforces removal of previous content before inserting new one.

In order to append the data, you have to explicitly specify the append mode.

Example:

#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;
}

Source: http://www.cplusplus.com/reference/fstream/ofstream/open/

In your case, you have to change it in this way:

outFile.open("personnel2.dat", std::ofstream::out | std::ofstream::app);
Kunal Puri
  • 3,419
  • 1
  • 10
  • 22