0

I've run into an issue with writing to a file and it being over written every time the program is ran. I can't seem to find a solution for the in.txt to stop wiping itself, so I decided to do something even better but more complicated.

Question: What can I look into to create a file for each entry from a person. I could retrieve the first and surname to name the file I guess.

I have a struct like this -

struct ClientInfo {

    string first_name;
    string middle_name;
    string surname_name;
    string date_birth;
    string telephonenumber;
    string first_line;
    string second_line;
    string zip_post; // zip code or postcode
    string Country;

};

When I start the program it records it into ofstream file_in("in.txt") successfully but then it's automatically erased at the start of next entry.

Stewart
  • 4,356
  • 2
  • 27
  • 59
  • What you are looking for is [How to append text to a file in C++](https://stackoverflow.com/questions/2393345/how-to-append-text-to-a-text-file-in-c) – OLP May 25 '20 at 20:17

1 Answers1

0

... but then it's automatically erased at the start of the next entry

To solve this issue, you need to use append mode not write. Try the following:

std::ofstream outfile;

outfile.open("myfile.txt", std::ios_base::app); // append instead of overwrite
outfile << "text";
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • Hello, thank you for the reply. I've tried that but it still over writes, could this possibly be because I'm using io redirection? – Zdenko Buvar Brazda May 26 '20 at 21:03
  • streambuf* stream_buffer_cout = cout.rdbuf(); streambuf* stream_buffer_cin = cin.rdbuf(); streambuf* stream_buffer_file = file.rdbuf(); cout.rdbuf(stream_buffer_file); cout << "this line written to file" << endl; cout.rdbuf(stream_buffer_file); cout << "this line is written to screen" << endl; copy(p_vec.begin(), p_vec.end(), std::ostream_iterator(std::cout, " ")); – Zdenko Buvar Brazda May 26 '20 at 21:05