如何在多个函数中操作 ifstream 对象

How to manipulate a ifstream object in multiple functions

本文关键字:操作 ifstream 对象 函数      更新时间:2023-10-16

我正在处理一个涉及解析 XML 文档的项目,我需要创建一个处理文件的打开和关闭函数。我有一个类,它有一个 ifstream 对象和两个关闭和打开的函数,它们使用相同的对象。问题是在打开函数中,对象默认是关闭的,直到程序到达关闭函数,它总是返回你没有打开文件,即使有一个文件打开。有没有办法使对象成为全局对象以创建它,以便它可以在两个函数中工作?任何建议不胜感激

 class CommandParser
   {
     private:
      std::ifstream inFile; 
      std::string pathAddress;
     ...
     ...
    public:
      void open(const std::string address);
      void close();
      void setPathAddress(const std::string newPathAddress);
};
//Defining file 
void CommandParser::open(const std::string address)
{
    inFile.open(address);
    if(!inFile.fail())
    {
        throw std::runtime_error("Invalid path! n");
    }
    else
    {
        setPathAddress(address); 
        std::cout << "Successfully opened the file ! n";
        parseFile();
    }
}
void CommandParser::close()
{
    if (inFile.is_open()) 
    {
        inFile.close();
        std::cout << "Successfully closed file! n";
    }
   else
       std::cerr << "You didn't open a file ! n";
}

如果操作失败,则会设置 fail 标志 – 因此,如果您成功打开文件,则不会设置它(除非之前已经设置过(。

所以好的情况是!inFile.fail(),但你扔那个...相反,您需要:

if( inFile.fail())
// ^ negation dropped!
{
    // error
}
else
{
    // success
}

或者更简单一点:

if(inFile)
{
    // success
}
else
{
    // error
}

旁注:您应该通过 const 引用接受字符串(否则,无论如何const都是没有意义的......

void open(const std::string& address);
//                         ^