Writing to a file in C++

To write data to a text file in C++, one solution is to use the put(char *content) function. This function is a member of ofstream class. See the example below:

#include<iostream>
#include<fstream>
using namespace std;
void writetofile(char *filename){
   char *chs="The Content of the file ..";
   ofstream out(filename,ios::app); //open the file
   if(!out){
         cout<<"Could not open the file!";
         return;
         }

   while(*chs) out.put(*chs++); //write text to the file using put(char *chs)
   out.close(); //close the file
  
   }

int main(){
   writetofile("C:\\myfile.txt");
   system("PAUSE");
   return 0;
}

Posted by: Ly | post date: 02-13-2013 | Subject: C++ Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.