Read File Line by Line in C++

Read file line by line in C++

C++ is a multi-domain programming language. It is widely used in embedded systems, game development, operating systems, etc. Therefore, we often come around situations where we need to read input from a file. Files are a great way to store the data permanently on the hard disk which is otherwise lost if the program exits. C++ elegantly handles reading from the files, writing to the files, and performing other operations. For this purpose, we have been provided inbuilt libraries with implemented functions. In this article, we will understand how to read a file line by line. 

Read File Line By Line in C++ Using the getline() Method

We can use the getline() method to read a file line by line in C++. For this, we will first create an input stream. After that, we will use the open() method of the file streams to open a file. 

  • The open() method takes the relative location or the absolute location of the file as a parameter and opens the file. 
  • Apart from the location of the file, it also accepts a second argument to denote the mode in which the file should be opened. By default, the file is opened in “ios_base::in | ios_base::out” mode. It means that if we do not provide any argument for mode, the file will be opened for reading as well as writing. 

The syntax of the open() method is shown below. 

After opening the file using the open()  method, you can use the is_open() method to check if the file has been opened successfully. The is_open() method, when invoked on a file stream, returns a boolean ‘true’ if the file is opened successfully. Otherwise, it returns false. Therefore, this method helps to handle situations where the file could not be opened due to some reasons. It helps us to avoid any error or unwanted output. 

Once we have successfully opened the file, we can read the file line by line using the C++ code.

  • To read the file contents one line at a time, we will use the ‘getline()’ function. 
  • The getline() function has two different signatures. In the first signature, the function takes the stream object as the first parameter and a string as the second parameter. It reads the file that has been opened using the stream passed to it and stores it into the string parameter. 
  • The other method signature of the getline() method requires a third parameter called ‘delimiter’. This parameter tells the function to stop reading the file when the passed character is found. 
  • By default, the getline() function reads until a newline ‘\n’ character is found or the end of the file is reached.  

The two different signatures of the ‘getline()’ method are given below.

We can use any of the given implementations as per our needs. In this article, we have to read the file line by line. Therefore, we will use the second method signature of the getline() method.

To read the file line by line in C++,

  • We will use the getline() function in a while loop that shall run till we reach the end of the file. 
  • As the end of the file is reached, the getline function returns null and the control moves out of the loop. 

In this way, we can read the file line by line in C++ using the getline() method. The C++ code to read a file line by line is given below.

Output:

You should provide the exact path of the file to the open() method. Also, if you are using the Windows operating system, make sure to follow proper file address conventions (Windows uses forward slash (‘\’) in filenames). 

Moreover, when we open a file, we should always close it to avoid memory leakage. You should use the ‘close()’ method of streams to close a file after we have performed all the tasks associated with the file.

Read File Line by Line in C++ Using C-style File Handling

C++ provides support to C-style file handling. We can make use of the C-style FILE pointer-based method to open our file. 

While using  the C-style method, 

  • We need to use the fopen() function to open the file. 
  • Also, the getline() method takes three arguments. 
    • The first argument is a character double-pointer that points to the character array that stores the content read from the file. 
    • The second argument is an unsigned integer pointer that represents the size of the character array.  The third argument is the file pointer.

Here, we will first open the file using the fopen() method. The fopen() method takes the file name as its first input argument and the literal ‘r’ as its second input argument to show that the file is opened in the read mode. After execution, it returns a FILE pointer.

After opening the file, we will read each line of the file using the getline() method and a while loop. Then, we will close the file using the fclose() method. The fclose() method takes the FILE pointer as its input argument and closes the file. 

We can read a file line by line using the C style approach discussed above as shown in the following example.

Output:

Conclusion

Files are widely used to store the data permanently. While working with the text files in C++, we often have to perform operations line by line. Therefore, we need to read the file line by line. In this article, we have understood the C++ streams and methods to open the files. We have understood, with an example code, to read the file line by line in C++. As a precaution, you should always close the file that we have opened so that you can avoid resource leaks. We have also seen C-style file handling that can come in handy when we have to write a portable code that works in a C environment as well.

I hope you have enjoyed reading this article. Stay tuned for more informative articles.

 Happy Learning. 

Was this post helpful?

Related Posts

  • 04 November

    Pass 2D Array to Function in C++

    Table of ContentsWays to Pass a 2D Array to function in C++Pass a 2D Array to a Function by Passing Its PointerPass an Array to the Function by Decaying the Pointer to the ArrayPass a 2D Array to a Function in C++ Without Size by Passing Its ReferenceConclusion Two-dimensional arrays have rows and columns, storing […]

  • 02 November

    Count Decimal Places in C++

    Table of ContentsAccuracy V/S Precision in Counting Decimal Places in C++ ProgramsHow to Count Decimal Places in C++Example 1: Use String Functions to Find Precise Number of Decimal PlacesExample 2: Count Decimal Places Accurately for a NumberExample 3: Create a Program that divides two numbers and returns their decimal placesExample 4: Find the Number of […]

  • 02 November

    Check if String Is Empty in C++

    Table of ContentsWays to Check if String Is Empty in C++Using Empty() methodUsing the Equality OperatorUsing length() methodUsing size() methodConclusion A String is a combination of characters that can store both alphabets and numbers together. In C, there was no concept of string as a datatype so character arrays were used. In C++, this drawback […]

  • 03 October

    Get Filename from Path in C++

    Table of ContentsGet Filename From Path in C++Using find_last_of and substr methodsUsing TemplatesUsing filesysystem library [ C++ 17 ]Conclusion This article explains the various ways to get filename from path using C++ programs. The examples will also describe ways to remove extensions as well if such needs arise. Get Filename From Path in C++ Finding […]

  • 24 September

    Escape Percent Sign in printf Method in C++

    In this post, we will see how to escape percent sign in printf Method in C++. Escape percent sign in Printf Method in C++ printf() method uses percent sign(%) as prefix of format specifier. For example: To use number in prinf() method, we use %d, but what if you actually want to use percent sign […]

  • 15 September

    Remove Last Element from Vector in C++

    Table of ContentsWays to Remove Last Element from Vector in C++Using the vector::pop_back() function to remove last element from vector in C++Using the vector::resize() Function to Remove Last Element from Vector in C++Using the vector::rrase() Function to Remove Last Element from Vector in C++Conclusion Learn about how to remove last element from Vector in C++. […]

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.