C++

EOF in C++

In file handling, we don’t know how much data is stored in the file. Since the extent of data in filing is mostly unknown, how can we read the file in that case? When we don’t know how much data the file contains, we use the eof() method to read a file. The eof() method is “End of File” which reads the file until the control reaches the end of the file. This methodology is very suitable to present the data of files. The things we know about the files are the type of file data and the formatting style of the stored data. The eof() function allows us to determine when the file has reached its end.

EOF() is a bool-type constant method that returns true when the end of the file is reached and it returns false when there is still data to be read. It is a method of input-output stream class (ios) that reads the data of a file until the end is encountered.

Syntax:

 

bool eof() const;

 
This method is a Boolean method of constant type, which means it cannot be changed. Either it returns true or false. This function has no parameters.

Return Type:

When it returns “true”, it means that the end is reached. When it returns “false”, it means that the end is not encountered yet.

Use EOF() to Read a File that is Already Created

The program reads the data from a text file. When it reaches the end, it displays a message. To do all these, we call the eof() function.

Create a File:

First of all, create a text file, “example.txt”. Add some content to it and then save the file. This file should be stored in a similar folder as the C++ code.


Code:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
   ifstream ist("example.txt");  
   char ch;
   while (ist.get(ch))                  
      cout << ch;
   if (ist.eof())                      
     cout << "[EoF reached]\n";
   else
      cout << "[Error Reading]\n";
   ist.close();                        
   return 0;
}

 
Now, let’s start coding. Import the <iostream> library to use the input and output functions of this library. Then, import <fstream> as file stream. We import this library so that we can access its methods. Call the main() method. Then, define “ifstream” which is the input stream. Create its object and give the location of a text file that we previously created or just write the name of that file. When the code file and text file are located in the same folder, we just mention the name of the file with its extension. Define a character type variable, “ch”. This variable gets the data from the string. Use the “while” loop to constantly read the file’s data until the end is reached. Inside the “while” loop, use the “cout” command to print the data. After displaying the entire data of the file, set the “if” condition. If the input stream “ist” reaches the end of the file, display the “EoF reached” message. Otherwise, execute the “else” portion. Print an error message “Error Reading” within the “else” portion. Then, close the file by calling the close() function.

Output:

hello world 360 [EoF reached]

 

Get the Data from the File

Let’s explain how we can get the data from a file and check the end of a file using eof().

Create a File:

Now, create a text file named “example2.txt”. Make sure that you save both the text and C++ files in the same folder. It will not cause issues while accessing the file. Here, we write the name of a few cities in the file. Save and close the file.


Code:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    char city_names[15];
    ifstream file("example2.txt");
    if(!file)
    {
        cout<<"Error while opening";
        exit(1);
    }
    cout<<"List of Cities in file : \n";
    while(!file.eof())
    {
        file>>city_names;
        cout<<city_names<<endl;
    }
    file.close();
    return 0;  
}

 
In the C++ code, import two libraries – <iostream> and <fstream>. After using the standard namespace, invoke the main() method and declare the “city_names” character type array. Then, set the size of the array that gets the array of characters from the text file. Create a “file” object of  the “ifstream” input file stream and give the name of the text file which is “example2.txt”. Now, use the “if” statement to check whether a defined file is opening or not. Print an error message if the file won’t open. Outside “if” statement, employ the “cout” command to show a “List of Cities in file” text. Furthermore, use a “while” loop to iterate in the file to get the data. Loop until the file is not reached at its end. To check the end of the file, call the eof() method. Get the file data inside the “while” loop and store it in the “city_names” character array. Then, display that array.

The file gets all the content that we store in the “example2.txt” text file and displays the data at the same time. Close the file outside loop. The closing of a file is important to prevent the file from any harm.

Output:

List of Cities in file :
Lahore
Karachi
Multan

 

Code to Acquire the Data from the User

In this example, we acquire the user’s data and enter it into a text file. Then, we display the data of that file on the console. To read the data from a file, we also use eof() which informs us when the file end is reached.

Create a Blank File:

First, an empty file, “example3.txt”, is created and saved in a folder. In this empty file, we store the data that the user gives us. Then, that data is read.


Code:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    char names[15];
    ofstream out("example3.txt");
    ifstream in("example3.txt");
    for(int i=0; i<3;i++)
    {
        cout<<"Enter Name :   ";
        gets(names);
        cout<<names<<endl;
    }
    out.close();
    cout<<"List of Names is : ";
    cout<<endl;
    while(!in.eof())
    {
        in.getline(names,100);
        cout<<names<<endl;
    }
    in.close();
    return 0;  
}

 
The most essential part of the code is including the libraries. In the main()function, define a character array of size 15. Create an “out” object of the “ofstream” output file stream. It provides the path/name of the empty text file. Then, create an “in” object of the “ifstream” input file stream. Use the “for” loop to get the string from the user. Here, print the “Enter Name:” message. Call the gets() method; it gets the string of names from the user, and the “out” ofstream object opens the file for writing. This ofstream object writes the names in the text file. Outside the “for” loop, close the “out” ofstream object because we are done writing. Show the “List of Names is:” text on the screen. Moreover, use the “while” loop and define its condition. Read the data from the file until the termination of a file is not attained. Employ the getline()function so we get the lines from the text file. Display those lines on the console. Outside the “while” loop, invoke the close() method of the “in” input file stream.

Output:

Enter Name :   Halibi
Enter Name :   John
Enter Name :   Nike
List of Names is :
Halibi
John
Nike

 
After Storing the Data:


After getting the names from the user and executing the C++ code, we open the empty file that we created. Here, we would see all the names. After the code execution, these names are stored in the “example3.txt” text file.

Conclusion

We discussed the eof() method in this article. EOF is the end of a file that is used while reading a file. We can determine when the file has ended by calling the eof()method. The article explains the topic on  EOF in C++ with the help of different codes in which we created the text file, entered the data in the file, and then read that data from the file. The eof() method is a Bool method, either it is true or false.

About the author

Sumayya Khan

I am a professional content writer. I have quite good experience in writing unique content for multiple programming languages. I've authored interesting and best-quality articles on technical niches.