Search code examples
c++ifstream

How to manipulate a ifstream object in multiple functions


I'm working on a project that involves parsing an XML document and I need to create a open and close function that works on files. I have a class that has a ifstream object and two functions close and open that use the same object. The problem is that in the open function the object is closed by default and until the programs reaches the close function it always returns You didn't open a file even though there is a file opened.. Is there a way to make the object a global object in order to create it so it can work in both functions ? Any suggestions are appreciated

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


Solution

  • The fail flag is set if an operation fails – so it won't be set if you successfully open a file (unless it already was set before).

    So the good case is !inFile.fail(), but you throw on that one... Instead, you'd need:

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

    Or a bit simpler:

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

    Side note: you should accept strings by const reference (otherwise, the const is meaningless anyway...):

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