Here is a small example of C++ code on how to read a characters from a file as well as to count the number lines of any particular file consist of. The code will check for "\n" the "new line character" and increase the number of lines stored in number_of_lines integer variable. Every iteration will also print single character including "\n" to an output.
First create a file called my-input-file.txt which will contain some text. For example:

welcome to

Then copy c++ code below to a file called read-characters.cpp:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

ifstream fin;"my-input-file.txt", ios::in);

char my_character ;
int number_of_lines = 0;

while (!fin.eof() ) {

cout << my_character;
if (my_character == '\n'){
cout << "NUMBER OF LINES: " << number_of_lines << endl;


and compile it with:

g++ read-characters.cpp -o read-characters

Execute new compiled binary file:


NOTE: your text file must be located in the same directory as your executable read-characters program.

NOTE: while loop and fin.get will add extra new line character so you may start with :

int number_of_lines = -1


welcome to


Free Linux eBooks

Do you have the right skills?

Our IT Skills Watch page reflects an up to date IT skills demand leaning towards the Linux and Unix environment. We have considered a number of skills and operating systems.

See the result...

Linux Online Training

Learn to run Linux servers and prepare for LPI certification with Linux Academy. 104 available video lessons with PDF course notes with your own server!

Go to top