0

How do I add new data to the file without destroying the old data? The data contains name and age fields. Here is my code:

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main() {
    char data[100];
    ofstream outfile;
    outfile.open("afile.txt");
    cout << "Writing to the file" << endl;
    cout << "Enter your name: "; 
    cin.getline(data, 100);
    outfile << data << endl;
    cout << "Enter your age: "; 
    cin >> data;
    cin.ignore();
    outfile << data << endl;
    outfile.close();

    ifstream infile; 
    infile.open("afile.txt"); 
    cout << "Reading from the file" << endl; 
    infile >> data; 
    cout << data << endl;
    infile >> data; 
    cout << data << endl; 
    infile.close();
    return 0;
}
r3mus n0x
  • 5,400
  • 1
  • 8
  • 30
youngah
  • 13
  • 5

1 Answers1

0

According to std::ofstream

void open (const string& filename, ios_base::openmode mode = ios_base::out);

where std::ios_base::openmode is one of the following

  • app (append) Set the stream's position indicator to the end of the stream before each output operation.
  • ate (at end) Set the stream's position indicator to the end of the stream on opening.
  • binary (binary) Consider stream as binary rather than text.
  • in (input) Allow input operations on the stream.
  • out (output) Allow output operations on the stream.
  • trunc (truncate) Any current content is discarded, assuming a length of zero on opening.

You can combine openmodes with |

std::ios_base::openmode::out | std::ios_base::openmode::app

This will open file for writing, appending data to the end.

Tarek Dakhran
  • 1,734
  • 5
  • 17
  • i dont understand . ok now u said i write this (std::ios_base::openmode::out | std::ios_base::openmode::app)? to solve my problem – youngah Feb 28 '20 at 22:38