C++ read from file

On way to read the content of a text file is using get(char ch) function. This function will read character by character from the file (until the end of the file is met) and place it in the ch argument. The example below shows you how to write text to the file called testfile.txt and how to read the file back.
#include<iostream>
#include<fstream>
using namespace std;
void writetofile(char *filename){
   char *str="This is a line of the file.\n";
   ofstream out(filename,ios::app);
   if(!out){
         cout<<"Could not open the file!";
         return;
         }
   while(*str) out.put(*str++);
   cout<<*str;
   out.close();
  
   }
void readfromfile(char *filename){
   char ch;
   ifstream in(filename,ios::in);
   if(!in){
         cout<<"Could not open the file!";
         return;
         }
   while(in.get(ch)){
                cout<<ch;
                   }
    
   in.close();
  
   }

int main(){
   writetofile("D:\\testfile.txt");
   readfromfile("D:\\testfile.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.