C++ read file line by line

In C++ to read a file line by line you can use get(char arr[],int size) function. This function will stop reading when the file delimiter is met or it reaches the size limit.
Example:
#include<iostream>
#include<fstream>

void readline(char *filename){
   int SIZE=100;
   char str[SIZE];
   int ln=0;
   ifstream in(filename,ios::in);
   if(!in){
         cout<<"Could not open the file!";
         return;
         }
   while(in.get(str,SIZE)){ //read characters from the file into str array
                    
                     cout<<str<<endl;
                     ln++;
                     in.ignore(); //by ignoring file delimiter, so you can read all lines in the file                
   }
   cout<<"Number of lines read:"<<ln<<endl;

   }
int main(){

   readline("D:\\testfile.txt");
   system("PAUSE");
   return 0;
}

Another way to read a file line by line is using getline(char arra[],int size) function. By using getline function you do not need to ignore the file delimiter. The file will be read until the end of the file. The default file delimeter is \n.
#include<iostream>
#include<fstream>
using namespace std;

void readline(char *filename){
   int SIZE=100;
   char str[SIZE];
   int ln=0;
   ifstream in(filename,ios::in);
   if(!in){
         cout<<"Could not open the file!";
         return;
         }

   while(in.getline(str,SIZE)){
                    
                     cout<<str<<endl;
                     ln++;
                     }
   cout<<"Number of lines read:"<<ln<<endl;
  
   in.close();
   }
int main(){
   readfromfile("D:\\testfile.txt");
   system("PAUSE");
   return 0;
}

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.