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

  • 19 May

    Get Type of Object in C++

    Table of ContentsWhy Should We Determine the Type of Object in C++: Dynamic DispatchingGet Type of Object in C++ConclusionWas this post helpful? C++ is an object-oriented language where we often interact with objects of different types. The object interaction becomes more interesting when we add runtime polymorphism to it. The runtime polymorphism, also known as, […]

  • 19 May

    Convert Vector to Array in C++

    Table of ContentsVectors and Arrays in C++Convert Vector to Arrays in C++Using the for loop to convert vector to array in C++Using the copy() function to convert vector to array in C++Using the transform() function to convert vector to array in C++Using the data() function to convert vector to array in C++Using the & operator […]

  • How to initialize an array in Constructor in C++
    23 April

    How to initialize an Array in Constructor in C++

    Table of ContentsArraysConstructors of a ClassWays to initialize an array in Constructor in C++Initialize an array in Constructor With std::fill()Initialize an array in Constructor Using for LoopInitialize an array in Constructor Using Member Initializer ListConclusionWas this post helpful? This article discusses methods of initializing an array in constructor in C++. Let us first discuss arrays […]

  • Write String to file in C++
    31 March

    Write String to File in C++

    Table of ContentsUsing the fstream Library to write String to File in C++Using the Insertion Operator (<<) With the fstream ObjectUsing the write() Function of the fstream LibraryUsing the fwrite() Function to write String to File in C++ConclusionWas this post helpful? The files are used to store the data permanently on a disk. This mitigates […]

  • Print Array in C++
    23 March

    Print Array in C++

    Table of ContentsIntroduction of ArraysDifferent Methods to Print an Array in C++print array in C++ by Traversing Indicesprint array in C++ Using for_each() Functionprint array in C++ Using Range-Based for Loopprint array in C++ Using Iteratorsprint array Using ostream_iterator() Function and copy() Functionprint array Using C++17 copy() Function and make_ostream_joiner() FunctionConclusionWas this post helpful? An […]

  • Print Vector C++
    23 March

    Print Vector in C++

    Table of ContentsPrint Vector in C++ Using IndicesPrint Vector in C++ Using Range-Based for LoopPrint Vector in C++ Using for_each() FunctionPrint Vector in C++ Using IteratorPrint Vector in C++ by Overloading the Insertion Operator (<<)Print Vector in C++ Using copy() FunctionConclusionWas this post helpful? This article discusses the vector and how to print vector in […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.