What is EOF?

EOFindicates “end of file” is a special delimiter or data that is placed at the end of a file after the last byte of data in the file.

The purpose of this delimiter is to indicate the end of file to file-reading programs. This is also useful for the storage and transmission of data.

Code

1. EOF file in C++

The following code detects the EOF in C++. It reads and displays each character in the file until it reaches the end of file delimiter. Once EOF is detected, it outputs it as well.

main.cpp
myfile.txt
#include <iostream>
#include <fstream>
int main () {
std::ifstream is("myfile.txt"); // open file
char c;
while (is.get(c))
std::cout << c;
if (is.eof())
std::cout << "[EoF reached]\n";
else
std::cout << "[error reading]\n";
is.close();
return 0;
}

2. EOF file in Python

The following code detects the EOF in Python. It reads and displays each character in the file until it reaches the end of file delimiter. Once EOF is detected, it outputs it as well.

main.py
myfile.txt
f = open("myfile.txt", "r")
while True:
line = f.readline()
if not line:
print("EoF reached")
break
print(line)

New on Educative
Learn any Language for FREE all September 🎉,
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources