ifstream object seems to be null

I'm trying to open a file and read its content but it seems that the ifstream object is null

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 DatabaseReader::DatabaseReader()
{
    std::string completePath = "DB.txt";
    std::ifstream DBFile;
    DBFile.open(completePath);
    if(!DBFile.is_open())
    {
        std::cout<<"Database file couldn't be opened :(\n"<<"Exiting......"<<std::endl;
        sleep(5);
        exit(1);
    }
}

DatabaseReader::~DatabaseReader()
{
    DBFile.close();
}

int DatabaseReader::getNumberofAvailableRecords()
{
    std::string recordCount;
    if(DBFile.good())
    {
        DBFile >> recordCount;
        std::cout<<"Number of Records (if): "<<recordCount<<std::endl;
        std::cout<<"DBFile : "<<(DBFile == 0)<<std::endl;
    }
    else
    {
        recordCount = "-1";
        std::cout<<"Number of Records (else): "<<recordCount<<std::endl;
    }
    std::cout<<"Number of Records : "<<recordCount<<std::endl;

    return std::stoi(recordCount);
}


When I run the program I get the following output:

1
2
3
4
5
6
7
Number of Records (if):
DBFile : 1
Number of Records :
terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi

This application has requested the Runtime to terminate it in an unusual way.


Since DBFile.good() was executed, I'd assume the file was opened. But (DBFile == 0) or (DBFile == NULL) prints 1.

Then when I attempt to check what was read from file into recordCount, "Number of Records :" prints out with no value. I'm expecting 2 since it's the first line in the file.

What am I doing wrong?
If your file exists then the file could be open, yet if the file is empty then the read of the recordCount could cause the stream to enter a failed state which will leave recordCount in it's default state (empty). Which is what appears to be happening since nothing is printed after the "(if): ".

Also look at the value of DBFile == 0 printout (1), which means that the stream is in a fail state.

By the way why is recordCount a string instead of some kind of number?
Last edited on
The DBFile object used to open the file is local to the constructor, so the file is closed after the constructor is finished.
I moved std::ifstream DBFile; outside the constructor, before the constructor, and now it's working. But I'm a bit confused. Isn't all initialization supposed to be done inside of the constructor? Why didn't the original code work?
Last edited on
Topic archived. No new replies allowed.