首页 > 解决方案 > rdstate() 函数返回值 3 用于在文件处理 C++ 中使用 eof() 函数的代码

问题描述

我在 Visual Studio 中的代码

在我的代码中,我使用了 eof(),然后我使用了 rdstate() 函数来应用条件来了解我是否已到达文件末尾,以便我可以清除()状态并将指针位置重置到 eof() 以外的其他位置。我使用 XOR ^ 运算符作为条件的另一件事,所以如果两者都是真的结果是假的,即我想要的。但这并没有发生,所以请让我知道我错在哪里。

文件名为 ALi.txt,包含 7 行文本。

#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";
    }
}

}

标签: c++eof

解决方案


推荐阅读