Write To File In C++

by Shabbir on April 30, 2008

in C/C++

In this post we explained writing in a file using the C# language. In this post we will explain how to do that in unmanaged C++.
So, we are creating a C++ console application, you can use Dev C++ for compiling this code.
Here is the code.

 
int main()
{
	ofstream fw;
	fw.open("text.txt");
	fw << "Some texxxxxxxxxt." << endl;
	fw << "tab\ttab, and a new line\n...." << endl;
}

We include the fstream library, it contains the ofstream and ifstream classes. They are used for writting and reading to/from files.
Then, in the main function we create an object from ofstream class, and with function open we tell the object that we will write in the file "text.txt".

We write some text to file (check the new line and tab characters).

In the end we close the handle.

This will be written in the file

Some texxxxxxxxxt.
tab	tab, and a new line
....

If you do not want to erase all text from the file and then write to it again, just make this change

fw.open("text.txt", ios::app);

Sharing is Caring...

Other Related Posts:

  1. Read From File In C++
  2. Write To File in C#
  3. Read From File Using StreamReader Class
  4. Functions in C++
  5. Read/Write Registry Keys

{ 2 comments… read them below or add one }

Unni March 30, 2010 at 3:15 pm

Hi I am an effective money maker(not online) by making softwares using VB Can i blog in code it well how to make money (not online) using Vb(visual basic)

Reply

Shabbir Bhimani March 31, 2010 at 2:08 am

We do not want spammers as bloggers.

Reply

Leave a Comment

Spam protection by WP Captcha-Free

Previous post:

Next post:

    About the Author

  • author photo

    My Name is Shabbir Bhimani and I am developer by profession in the field of applications, web and database. Currently doing full time online marketing and like to share my experiences on how you can make money online @ CodeItWell.com. Read more ...


    See how you can get in touch with me.