By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,491 Members | 1,108 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

How to read a text file - C++

P: 7
This article is the second part of the article I made earlier on how to create a text file.

In this article you will be learning how to read the text file that we created, I will be teaching you how to put this code with the code we made but if you want to put it into a different project or source file and compile it separately that will work also.

Now lets start the code:
You should already have this in your source file:
Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<fstream>
  3.  
  4. using namespace std;
  5.  
  6. int main() {
  7.  ofstream Myfile;
  8.   Myfile.open ("test.txt");
  9.   Myfile << "This is a test.";
  10.   Myfile.close();
  11.  
  12.   return 0;
  13. }
  14.  
I did change myfile to Myfile with a capital for this tutorial.

1-> Made a space under "Myfile.close();" to make your code look cleaner and put in:
Expand|Select|Wrap|Line Numbers
  1. ifstream myfile;
  2.  
ifstream provides an interface to read data from files as input streams.

2-> Under that open your file.

Expand|Select|Wrap|Line Numbers
  1.  myfile.open("test.txt");
  2.  
3-> Now create a char, we are going to call our char "Output".

Expand|Select|Wrap|Line Numbers
  1.  char output[100];
  2.  
4-> Now create an 'if' statement.

Expand|Select|Wrap|Line Numbers
  1. if (myfile.is_open()) {
  2.  
  3. }
  4.  
5-> Inside the 'if' statement output the contents of your text file using the char.

Expand|Select|Wrap|Line Numbers
  1.  while (!myfile.eof()) {
  2.  
  3.     myfile >> output;
  4.     cout<<output;
  5.  }
  6.  
6-> Now, under the if statement close your text file.

Expand|Select|Wrap|Line Numbers
  1. myfile.close();
  2.  
Your code (If you did the first article also) should look like this:

Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<fstream>
  3. using namespace std;
  4.  
  5. int main() {
  6.  ofstream Myfile;
  7.   Myfile.open ("test.txt");
  8.   Myfile << "Hello";
  9.   Myfile.close();
  10.  
  11.  ifstream myfile;
  12.  myfile.open("test.txt");
  13.  char output[100];
  14.  if (myfile.is_open()) {
  15.  while (!myfile.eof()) {
  16.  
  17.     myfile >> output;
  18.     cout<<output;
  19.  }
  20. }
  21. myfile.close();
  22. getchar();
  23. getchar();
  24. return 0;
  25. }
  26.  
If I missed anything please comment and tell me.

If you have any problems or want to know anything feel free to inbox me or email me at: <email address removed>
Dec 14 '11 #1
Share this Article
Share on Google+