iTech College - Internet Technology, Online Education, E-Learning, Technician Training, Tech Tutorials, Distance Education, Virtual Learning C++ Course: Read and Write a Text File - www.itechcollege.com C++ Course: Read and Write a Text File - www.itechcollege.com
Free Courses
HTML
JavaScript
CSS
ASP
PHP
JSP
C++
ASP.NET
SQL
AJAX
FTP
XML

courses > C++ > Read and Write a Text File

Read / Write a Text File

How to read a text file using C++? Here is an example:

Let's create a text file "myTest.txt", and type the following lines:

This is a test file
This is the second line of the test file

Then let's write a C++ program to read this file:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
   string line;
   //using ifstream to input file stream from a text file
   ifstream myfile ("myTest.txt");
   
   if (myfile.is_open())
   {
		while (! myfile.eof() )
		{
			getline (myfile,line);
			cout << line << endl;
		}
		
		myfile.close();
   }
	else cout << "Can't open file"; 
	
	return 0;
}

To write strings to a text file, we can write a program like this:

#include <iostream>
#include <fstream>
using namespace std;
int main () {

	//using ofstream to output strings to a text file
   ofstream myfile ("myTest.txt");

   if (myfile.is_open())
   {
   	myfile << "This is a test.\n";
   	myfile << "I am learning C++.\n";
   	myfile.close();
   }
   else cout << "Can't open file";

   return 0;
}

In the above two examples, we include Stream class "fstream" as a header file to both read and write from/to files. Then for reading (input) from a text file, we use "ifstream" , for writing (output) to a text file, we use "ofstream".



  Back to Index Page
 Next Page:  

Include a File and Main Function
Output and Input Data
Variables
Arrays
Operators
The If Statement and The Switch Statement
Loops
Function
Read and Write a Text File
Using Database MySQL
Drawing and Graphics


Online Education, Online Training for Your Job, Distance Education, E-learning Programs for Your Career!Online Colleges, Online Universities, E-learning & Distance Education for Your Career! Easy Job Training & Online Courses.


   Email A Friend  
 
Earn Online Degree
for Your Job
I found a job after I earned an online degree!
Online classes for finding a Job. Online College, Online University, Degrees, E-learning school, online certificate Earn your
online degree now!
Online Training
for Good Job
Why I work so hard but earn so little? Why I cannot find a high paying job?
Online training for a Good Jobs. Online Degree, E-learning school, online certificate Go to
online school now!

Copyright ©2024, itechcollege.com. All rights reserved
iTechCollege | About iTech | Contact iTech