Reputation: 3329
I'm trying to read some values from a config file in c++ and getline
doesn't seem to be working.
The relevant portion of the code looks like this:
#include <iostream>
#include <fstream>
#include <unistd.h>
using namespace std;
// ...
ifstream config( configPath );
string line;
Message( DiagVerbose, "CONFIG: %s\n", configPath.c_str());
bool exists = ( access( configPath.c_str(), F_OK && R_OK ) != -1 );
Message( DiagVerbose, "Exists?: %s\n", exists ? "true" : "false");
// This was causing a fail bit to set
//config.open( configPath );
if (config.is_open())
{
Message( DiagVerbose, "Config is open%s\n", config.good() ? "good" : "bad" );
while ( getline( config, line ) )
{
Message( DiagVerbose, "Line: %s", line.c_str());
extension_t extension = parseConfig( line );
extensions[ extension.name ] = extension.type;
}
config.close();
} else {
FatalError( "Could not open file %s\n", configPath.c_str());
}
The Message function is just a wrapper for printf and prints the following:
CONFIG: ./tool.conf
Exists?: true
Config is open: good
74181 Segmentation Fault: 11
But everything in the while loop is skipped. Also the file I'm reading from does actually have data in it.
Why is getline
not getting the line even though the file exists and is readable?
UPDATE
I changed the code above to reflect the changes suggested by @rici however, now I'm facing a Segmentation Fault at the same line before anything in the while
loop is called.
Upvotes: 0
Views: 2527
Reputation: 536
You opening same file twice
Remove the
config.open( configPath );
before
if (config.is_open())
Upvotes: 0
Reputation: 241671
You're opening config
twice (once in the constructor, and again using an explicit open
). The second open
is an error, which causes the failbit to be set (even though the ifstream is still open.) From then on, all I/O operations to the ifstream
will fail.
Upvotes: 7