Open a file in C++

In C++, there are two ways to open a file for writing, reading, or appending. The first way is using the constructor of ofstream, ifstream, or fstream class.
Example:
char *filename="myfile.txt";
ofstream out(filename,ios::out); //open the file for writing
......................................................................
char *filename="myfile.txt";
ifstream in(filename,ios::in); //open the file for reading
......................................................................
char *filename="myfile.txt";
ofstream ap(filename,ios::app); //open the file for appending
......................................................................
char *filename="myfile.txt";
fstream rw(filename,ios::in|ios:out); //open the file for both reading and writing


The other way is using open(filename,mode) function of the ofstream, ifstream, or fstream class.
Example:

char *filename="myfile.txt";
ofstream out;
out.open(filename,ios::out); //open the file for writing
......................................................................
char *filename="myfile.txt";
ifstream in;
in.open(filename,ios::in); //open the file for reading
......................................................................char *filename="myfile.txt";
ofstream ap;
ap.open(filename,ios::app); //open the file for appending
......................................................................
char *filename="myfile.txt";
fstream rw;
rw.open(filename,ios::in|ios:out); //open the file for both reading and writing

Posted by: Dara | post date: 02-12-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.