I have a small code with some file I/O
bool loadConfigFile(std::string configFileName)
{
std::ifstream configFile;
try
{
configFile.open(configFileName, std::ifstream::in);
if(true != configFile.good())
{
throw std::exception("Problem with config file");
}
} catch (std::exception &e)
{
fprintf(stderr, "There was an error while opening the file: %s\n %s\n" , configFileName, e.what());
configFile.close();
}
configFile.close();
return true;
}
And everytime I launch the program without the file provided as a parameter I get some rubbish on output (random characters) or an unexpected error in runtime. What am I doing wrong here ?
"%s"expects an null terminatedchararray as its input but the code is passingconfigFileName, which is astd::string. Either usestd::string::.c_str()or usestd::cerrinstead:Note that the
ifstreamconstructor has a variant that accepts the filename to open and the destructor will close the stream if it is open so the explicit calls toopen()andclose()can be omitted: