Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
What code is used to write a file without overwriting the already written content. Taking an example the following code:
C++
using namespace System;
using namespace System::IO;

int main()
{
    //creating the file object data.txt
    FileStream^ fs = gcnew FileStream("data.txt", FileMode::Create);
    StreamWriter^ sw = gcnew StreamWriter(fileName);
    try
    {
        //writing lines from a string and a textbox input
        sw->WriteLine("First Name: "+ this->FnameTextBox->Text);
    }
    //Exception handler
    catch (Exception^)
    {
        Console::WriteLine("data could not be written!");
        fs->Close();
        return -1;
    }
    fs->Close();
    return 0;
}

The above code overwrites the content of the file data.txt.
What code should I add in order to write new content starting from the next line of the text file?

Thanx in advance for any help that you'll give me.
Posted
Updated 29-Apr-11 5:24am
v2

A proper combination of FileModes should do the trick. Read about it here: http://msdn.microsoft.com/de-de/library/system.io.filemode(v=VS.80).aspx[^]

C#
using namespace System;
using namespace System::IO;

int main()
{
    // Writing the file object data.txt
    // FileMode::Append only in combination with FileMod::Write
    FileStream^ fs = gcnew FileStream("data.txt", FileMode::Write | FileMode::Append);
    StreamWriter^ sw = gcnew StreamWriter(fileName);
    try
    {
        //writing lines from a string and a textbox input
        sw->WriteLine("First Name: "+ this->FnameTextBox->Text);
    }
    //Exception handler
    catch (Exception^)
    {
        Console::WriteLine("data could not be written!");
        fs->Close();
        return -1;
    }
    fs->Close();
    return 0;
}



Best Regards,

-MRB
 
Share this answer
 
v2
Comments
HimanshuJoshi 29-Apr-11 11:31am    
Great minds and all! You seem to have beat me to the answer. Take a 5.
Manfred Rudolf Bihy 2-May-11 6:33am    
Thank you!
Change
FileStream^ fs = gcnew FileStream("data.txt", FileMode::Create);

to
FileStream^ fs = gcnew FileStream("data.txt", FileMode::Append | FileMode::Write);


In other words, open your file in append mode will allow you to write it at end of file.
 
Share this answer
 
v3
Comments
Joan M 29-Apr-11 11:31am    
simple and direct... my 5.
HimanshuJoshi 29-Apr-11 12:04pm    
Thanks.
Albert Holguin 29-Apr-11 14:12pm    
less clutter... :)
HimanshuJoshi 2-May-11 9:49am    
Thanks!
Manfred Rudolf Bihy 2-May-11 6:34am    
My 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900