0

My code in Visual Studio

In my code i used eof() then i used rdstate() function to apply condition of getting to know if i have reached end of file so that i can clear() state and reset pointer position to somewhere else than eof(). One more thing i have used XOR ^ operator for condition so if both are true result be false i.e what i want. But it is not happening so kindly let me know where i am wrong.

File name is ALi.txt and contains 7 lines of text.

#include <iostream>
#include <fstream>

int main()
{

{
    std::fstream file;
    file.open("Ali.txt",std::ios::in);
    
    if (file.is_open()) {

        std::cout << "The File has been opened Successfully " << "\n";


        std::string str;

        /* Fail()function can also be replaced with good ufucntion which returns true if everything is working fine | False otherwise */
      
        while (!file.eof()) {
            
            file >> str;
            std::cout << str << "\n";
        }
        std::cout << std::ifstream::eofbit << "\n" << std::fstream::failbit << "\n" << std::fstream::failbit << "\n";
        
        /*If a bad state happened like above then you need to clear it using clear() function to work further like Reading through File*/

        //std::cout << filehandler.good() << "\n";            // It is returning 0 | False here. Now to check which of above fu=nction is causing it 
        /*using rdstate() function. fail(4) , eof(2) and Bad(1) bytes*/

        std::cout << (file.rdstate() ^ std::ifstream::eofbit) << "\n";
        if ((file.rdstate() ^ std::ifstream::eofbit) == 0) {
            std::cout << "It is an indicator that we have reached the end of file So now we should do something to go back to begining of file " << "\n";
            file.clear();
        }
        file.close();
    }
    else {
        std::cout << "The File has been Failed to open" << "\n";
    }
}

}

  • you should include your code as text in the quesiton. – 463035818_is_not_an_ai Jul 09 '20 at 13:09
  • `eof()` returns a `bool`, not an `int`. So it can only possibly return `false` or `true`, which, when printed as integers, show up as `0` or `1`. It can't possibly return `2`. – Igor Tandetnik Jul 09 '20 at 14:15
  • As to why your program is "not working". It would help if you explain in what way it's not working - what outcome do you expect, and what do you observe instead? Anyway, my crystal ball says it's likely [this](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Igor Tandetnik Jul 09 '20 at 14:17
  • `^` is not the correct test to see if a bit is set it should be `&`. – john Jul 09 '20 at 14:29
  • Yes eof() returns true but then why is my condition not working because the fstream::efobit returns 2 and since eof() is used in code then rdstate is also supposed to return 2 but it is not happening – Syed Sibteali Baqar Jul 09 '20 at 17:11

0 Answers0