Count lines in file in C++

Count lines in file in C++

We often store our data into files when we need the data to be persistent and written into the hard disk. Files can be used to store many types of data including text, numbers, images, etc. The files store text data line by line where each line can have multiple characters and words. You may need to count the number of lines in a file on various occasions. In applications such as text editors, line numbers are usually mentioned before each line of the file. In this article, we will discuss how to count the number of lines in a file.

How To Count Lines In A File In C++?

To count the lines in a file in c++, we will open the file in the read mode only as there are no output operations needed. Once the file is open we will read the file line by line using the getline() function and count the number of lines. The getline() function takes a file stream as its first argument and a string variable as its second argument. Upon execution, it reads the next line in the file stream into the string variable. After that, it advances the file pointer.

Before writing the program, let us see how a text file looks internally. It will help us to understand how our program works. 

You can observe that after each line, a newline character (\n) has been inserted automatically. At the end of the text file, there is an end of file indicator (EOF). In our program, we will read the file line by line until we reach the end of file or EOF.  

To check whether we have reached EOF or not, we will use the peek() method. Just as we peek into something to get any info about what’s happening without letting someone know about it, the peek() method, when invoked on a file stream, reads the next character without advancing the file pointer. Once the peek() method reads the EOF character, we will stop counting the number of lines in the file.

C++ Program To Count Lines In A File

Let us now implement a C++ program to read the file and count the number of lines in it using the getline() function and peek() method in C++. 

The output of the above program is given below.

  • In this program, we have used the ifstream constructor to create the file stream object to open the file. 
  • We have declared a string variable to input the filename. The user is prompted to enter the name of the file which he or she wants to read and count lines in it. If the file is not present in the directory as the code file then provide a complete path of the file for the program to work correctly. 
  • The program handles errors in opening the file by showing an appropriate message when for some reason the file could not be opened using the.
  • Next,  we have declared a line variable to read each line from the file and a ‘count’ variable to keep the count of the number of lines in the file. 
  • In the next line, we open the file using the ifstream object constructor by passing the name of the file into the constructor. 
  • Then we check if the file has been successfully opened using the is_open() method. If so, we are ready to read the file otherwise we will display a message to the user that the file hasn’t been opened. 
  • We then read the file in a loop using the peek() method and the getline() function. Here we check if the next character to be read is the EOF (end of file) character or not, using the peek() method. Until we reach the end of the file, we read the file line by line and increase the count.  Finally, we display the count of lines. 

How To Count Lines In A File In C++ Using C-style Approach?

There is an alternative way to count the number of lines in a file in C++. We can use C-style file handling to read the file and count the number of lines in it. For this, we can open a file using the fopen() method and store the file pointer to a FILE pointer object. The fopen() method accepts two arguments, the first argument is a character array denoting the filename and the second argument is the parameter indicating the mode of opening the file. We will open the file in read-only mode. 

In this method, instead of reading each line at a time, we read each character at a time and check if the character is a newline character (\n). Each time we find a newline character, we consider it to have completed a line and we increase the count of lines in the file. Here, we will read the characters from the file using the getc() function. The getc() function takes the file name as input and returns the next character in the file.

In the end, we break from the loop when the end of file (EOF) character is found. We will use the same file used above for counting the number of lines.

C++ Program to Count Lines In A File using C-style approach

Let us now implement a program using the getc() function to count the number of lines in a file in C++. 

The output of the above program is given below.

  • In this program, we have used C-style file handling to open the file and count the number of lines into it. 
  • First, we declare a character array of size 256 characters to hold the name of the file. This size is arbitrary and you can increase or decrease it as needed.
  • The program prompts users to enter the name of the file. Provide the complete path of the file if the file is not present in the same directory as the code file. Otherwise, the program will not work as desired.
  • We declare a character variable ch to hold the character that is read each time in the loop and an integer variable count to count the number of lines in the file.
  • In the loop we read each character one by one, using the getc() method, and check if the character is not an EOF (end of file) character. If the character is EOF, we exit the loop. 
  • In the loop, each time the getc() function reads the newline character, we increase the count of the number of lines by one. 
  • Finally, when the loop is over, we display the count of lines in the file to console output. 

Please be aware that the program reads the number of lines from the file and if there are empty lines (caused by empty enter pressing), then those lines will be counted as well. 

Conclusion

Files are a necessary part of data storage and multiple types of data are stored in files for persistent storage. We often come across applications to read lines in files. In this article, we have understood how to read the files and count the number of lines in file in C++ using two ways.

That’s all about how to count lines in C++.

Related Posts

  • Read CSV file in C++
    01 November

    How to read CSV file in C++?

    Table of ContentsWhat is a CSV File? How To Read A CSV File In C++?C++ Code To Read A CSV FileHow To Read A CSV File Using C-Based Approach?Conclusion CSV files or Comma Separated Value Files are simple yet special files that we use to store data. Here, each value is separated by a comma, and […]

  • Get Number of Elements in Array in C++
    08 October

    Get Number of Elements in Array in C++

    Table of ContentsGet Number of Elements in Array in C++Using the sizeof() functionUsing the pointersUsing the size() functionGet the frequency of each element in array in C++Using nested for loopUsing maps One of the most fundamental collections in any programming language is an array. It stores a similar type of data at specific indices that […]

  • Trim String in C++
    19 July

    Trim String in C++

    Table of ContentsUsing Boost string algorithms to trim string in C++Using find_first_not_of() and find_last_not_of()` to trim strings in C++Using find_if() to trim the string in C++Using stringstream to trim the strings in C++Using a customized function to trim the strings in C++Conclusion When we take an input from an user, strings can have unwanted whitespaces […]

  • JSON parser in C++
    19 July

    JSON Parser in C++

    Table of ContentsSimple JSON Parser in C++ using JsonCpp libraryConclusion In this post, we will see about JSON parser in C++. There is no native support for JSON in C++. We can use a number of libraries that provide support for JSON in C++. We will use JsonCpp to parse JSON files in C++ which […]

  • Enum to String in C++
    19 July

    Convert enum to string in C++

    Table of ContentsUsing stringify macro method to convert enum to String in C++Using const char* Array to convert enum to String in C++Using a custom-defined function to convert enum to String in C++Conclusion There are a variety of methods to convert enum to String in C++. In this article, we will discuss some of the […]

  • C++ random number between 0 and 1
    11 June

    C++ random number between 0 and 1

    Table of ContentsUsing the rand() function to generate random number between 0 and 1 in C++Using the std::uniform_real_distribution() function to generate random number between 0 and 1 in C++ Random numbers are frequently used in programming for test case generation, cryptography, and other related purposes. In this tutorial, we will generate random number between 0 […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.