Question:
When using the code
while(!feof(file))
{
// Чтение из файла
}
in C or
while(!file.eof())
{
// Чтение из файла
}
in C++ you get into trouble – an extra read line, for example. Why? How to correctly check that the end of the file has been reached?
Answer:
The sign of reaching the end of the file is set only after an unsuccessful attempt to read beyond its end . Therefore, if the body of the loop does not check whether the reading from the file was successful, the last reading will turn out to be exactly the unsuccessful reading that will set the sign of the end of the file reached (and for you it will look like, for example, the last line read again, if it was in the read buffer).
It is better to perform the reading itself with a check in the head of the while
– for example, in a C program it could look like this
while(fread(&data,sizeof(data),1,file)==1)
{
// Обработка считанных данных
}
/* Или, скажем,
while(fgets(buf, bufsize, file)) { .... }
*/
if (feof(file)) // Достигнут конец файла
puts("Ошибка чтения: достигнут конец файла");
else if (ferror(file)) {
puts("Ошибка чтения файла");
or C ++ – resemblance
for(int n; file >> n; )
{
// Обработка считанного значения n
}
if (file.bad())
std::cout << "Ошибка ввода-вывода при чтении\n";
else if (file.eof())
std::cout << "Достигнут конец файла\n";
else if (file.fail())
std::cout << "Неверный формат данных\n";