简体   繁体   中英

fstream.open() set failbit


I've a problem accessing a file with fstream. Here is the code

 Conf::Conf()
{
  log = Log::Instance();
  _db_user = "";
  _db_password = "";
  _db_tableName = "";

  _treat["db:user"] = &Conf::set_db_user;
  _treat["db:adress"] = &Conf::set_db_adress;
  _treat["db:password"] = &Conf::set_db_password;
  _treat["db:tableName"] = &Conf::set_db_tableName;
  _treat["broadcast:adress"] = &Conf::set_broadcast_adress;

  _file.open("/home/borne/BorneApp/borne.conf", std::fstream::in);
  if (!_file.is_open())
    log->logThis("Error while opening borne.conf", "[INIT]", Log::ERROR);
}


void Conf::extract()
{
  std::string tmp = "";

  while (std::getline(_file, tmp))
  {
   if (_treat.find(tmp.substr(0, tmp.find("="))) != _treat.end())
    callMember(this, _treat[tmp.substr(0, tmp.find("="))])(tmp);
   else
     log->logThis("Parse Error in your configuration file", "[CONF]", Log::WARNING);
   }

}

getline return me nothing

So i have check if i have some error and... _file.fail() is set to TRUE

Facts : file is open properly.
I launch the program from /home/borne/BorneApp/
when i change this

_file.open("/home/borne/BorneApp/borne.conf", std::fstream::in);

to this :

_file.open("./borne.conf", std::fstream::in);

Everything works fine.

I don't uderstan why i've got that fail bit, can you help me?

If I understand well, _file.is_open() and _file.fail() both return true .

My guess is that the fstream is already associated with a file (ie you already called open on it for some reason).

If the stream is already associated with a file, calling open on it fails.

Here is a simple example:

#include <fstream>
#include <iostream>

int main(int argc, char **argv)
{
  std::fstream fs;
  fs.open("test.txt", std::fstream::in);
  if(!fs.is_open())
    std::cout << "Not opened" << std::endl;
  if(fs.fail())
    std::cout << "Failed" << std::endl;
  fs.open("test2.txt", std::fstream::in);
  if(!fs.is_open())
    std::cout << "[2] Not opened" << std::endl;
  if(fs.fail())
    std::cout << "[2] Failed" << std::endl;
  return 0;
}

Running it prints [2] Failed , which corresponds to what you describe. If the file couldn't be opened, _file.is_open() would reply false as this example shows when test.txt is suppressed or read permissions are removed from it.

So something in your code is probably making open being called twice. Is it called somewhere else than in the constructor of Conf in your code ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM