Table of Contents
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.
1 2 3 |
void open (const char* filename,ios_base::openmode mode = ios_base::in | ios_base::out); |
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.
1 2 3 |
istream& getline (istream& is, string& str, char delim); |
1 2 3 |
istream& getline (istream& is, string& str); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <fstream> using namespace std; int main() { ifstream file; file.open("/home/stark/eclipse-workspace/Aditya/src/sample.txt"); if(!file.is_open()) { cout<<"Unable to open the file."<<endl; return 0; } string line; while(getline(file, line)) { cout<<line<<endl; } file.close() return 0; } |
Output:
1 2 3 4 5 6 7 |
stark@stark:~/eclipse-workspace/Aditya/src$ g++ linebyline.cc stark@stark:~/eclipse-workspace/Aditya/src$ ./a.out Hello, this is first line. This is second line. This is last line. |
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.
Further reading:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <fstream> using namespace std; int main() { FILE *file = fopen("/home/stark/eclipse-workspace/Aditya/src/sample.txt", "r"); char *line; size_t len=0; while(getline(&line, &len, file)!=-1) { cout<<line; } fclose(file); return 0; } |
Output:
1 2 3 4 5 6 7 |
stark@stark:~/eclipse-workspace/Aditya/src$ g++ linebylinec.cc stark@stark:~/eclipse-workspace/Aditya/src$ ./a.out Hello, this is first line. This is second line. This is last line. |
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.