-1

Here is the code . It is giving the EXACT output as shown below means it is reading the file. But it is also showing fails as you can see it means fin.fails() is true. I want to know why this is true although i am successful in reading the file.

#include<fstream>
#include<iostream>
using namespace std;
int main()
{   ifstream fin;
    fin.open("pro.txt");
    char ch;
    int data;
    while(!fin.eof())//!(fin >> ch).eof()
    {
        fin.get(ch);
        cout<<ch;
        if(fin.fail()) {
            cout<<"fails";
        break;
        }
    }
    fin.clear();
    fin.seekg(0);
    int pos=(int)fin.tellg();
    cout<<"\n this is :"<<pos;
    fin.close();
    return 0;
}

Output is :
this is my name
fails
this is 0

Contents of pro.txt:
this is my name

Don't know why this is happening!

akitsme
  • 41
  • 11

2 Answers2

0

Still can't find why the fin.fails() is true because i think no one willing to But i figured out to read white spaces and file without making fin.fails() =true . just replace the while(!fin.eof()) with while(fin.get(ch)) and remove the fin.get(ch) present in while body -> this was the reason why my output was skipping one character for each read.. this i had mentioned in the comments.

akitsme
  • 41
  • 11
0

The problem is the following: Reading the last character in your file with get will not set the eofbit, so the call to fin.eof() in your while condition still returns false after you read the last character of the file inside the loop body. Then during the iteration following the read of the last character you try to read another character inside the loop body, even though there is no character to read anymore. This will set the eofbit and the failbit as per specification of get.

TL;DR: Reading over the end of a file is supposed to set the failbit.

Corristo
  • 4,111
  • 1
  • 16
  • 32