fail() Function in file streams

I have this below piece of code where I am reading a file line by line and printing the contents. The contents are printed properly but everytime I run the program, the failbit is set. Any problem with the program?? Please help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char finalLine[255];
memset (finalLine, '\0', sizeof(finalLine));
inputFile.open ("test.txt");

if (inputFile.open())
{
    while((!inpurFile.eof()) || (!inputFile.fail()))
    {
         inputFile.getline(finalLine,255);
         cout << finalLine << endl;
    }
    if (inputFile.fail())
    {
	cout << "Error while reading file test.txt" << ". errno = " << strerror(errno) << endl;
    }
}



Output:
Contents are printed fine. But the following statement is also printed.
Error while reading file test.txt. errno = Error 0

Why is this line getting printed?

Last edited on
Why is this line getting printed?
Because you read beyond the end of file (the errno isn't set in this case)
Last edited on
@coder777

Any better way to implement this? I want to prevent reading beyond EOF.

Thanks in advance.
Last edited on
there's no problem reading beyond eof. just don't cout the result.

you may write it like so:
1
2
3
4
5
6
7
8
    while(inputFile.getline(finalLine,255))
    {
         cout << finalLine << endl;
    }
    if (inputFile.fail() && (!inputFile.eof()))
    {
	cout << "Error while reading file test.txt" << ". errno = " << strerror(errno) << endl;
    }



btw: the better getline is this:

http://www.cplusplus.com/reference/string/getline/

with strings

Why is this line getting printed?

There can be two reasons:
1. istream::getline() encountered a line in your file that was more than 254 characters in length. It sets the failbit if it fails to get the entire line.
2 istream::getline() was unable to extract *any* characters, the file was empty or already at the end (your case), there was nothing more to read. It sets both eofbit and failbit in that case.

std::getline (the one that writes into strings) does the same thing when called with an empty file or file at end.

Based on you looking at errno, I think you meant to check for the badbit, not the failbit. The conditions that set failbit have no effect on errno in any case.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
    string finalLine;
    ifstream inputFile("test.txt");

    while(getline(inputFile, finalLine))
    {
         cout << finalLine << '\n';
    }

    if (inputFile.bad())
    {
        cout << "Error while reading file test.txt: " << std::strerror(errno) << '\n';
    }
}



PS: that memset() looks silly: first, you can initialize arrays to zero, second, you don't need to initialize them anyway if you're using istream::getline().
Topic archived. No new replies allowed.