Gitdown
Gitdown

Reputation: 13

Writing and saving text into a file c++ visual studio

So here's this code :

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                 mn=textBox1->Text;
                 MessageBox::Show(mn+" "+tsk, "Info" );
                 String^ fileName = "records.txt";
                 StreamWriter^ sw = gcnew StreamWriter("records.txt");
                 sw->Write(mn,tsk);
                 sw->Close();
             }

Everytime I try to write something new into the file from the program, it just writes the new text and doesn't keep old. How can I save it, so it doesn't delete ?

Upvotes: 0

Views: 817

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148870

The documentation for StreamWriter constructor states that you must set the append parameter to true to avoid a mere overwrite of the file. Your code should be:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
             mn=textBox1->Text;
             MessageBox::Show(mn+" "+tsk, "Info" );
             String^ fileName = "records.txt";
             StreamWriter^ sw = gcnew StreamWriter("records.txt", true); //append to file
             sw->Write(mn,tsk);
             sw->Close();
         }

Upvotes: 1

Related Questions