AaronC
AaronC

Reputation: 1

ifstream.fail() returns true after open()

Why does fin.fail() return true in the following code?

void loadName(){
    int pointer; //holds size of file
    fin.open("C:\\Users\\iAMspecial\\Desktop\\Names.txt", ios::app);
    if (fin.fail()) {
        cerr << "could not open intput file names.txt" << endl;
        system("pause"); 
        exit(1);
    }
    pointer++;
    getline(fin,Names[pointer]);
    for(int ndx = 0; !fin.eof(); ndx++){
        pointer++;  
        getline(fin,Names[pointer]);
    }
    fin.close();
    counter = pointer;
}

I've been struggling with std::ifstream in this function. I've scouted the other questions and even with all the advice, I can’t seem to get the function working.

A lot of the issues also seem to stem from Visual Studio, however I'm using a different IDE. Apologies in advance if I missed something really stupid.

I've made doubly sure of the file path, it is 100% correct. I'm truly stumped.

Picture of output:

Picture of output

The program is quite long, however if any other parts of it are relevant to the issues I'm having I'm happy to post it.

(Also note that the file path is temporary, I'm merely trying to have the function work, at that point I will have it work with different file paths).

Upvotes: 0

Views: 1460

Answers (2)

OriBS
OriBS

Reputation: 732

Every system call that fails update the errno value.

You can have more information about what went wrong if you will print it:

cerr << "Error: " << strerror(errno);

Upvotes: 0

Shreevardhan
Shreevardhan

Reputation: 12641

Use fin.is_open() instead. fin.fail() is not for checking stream open errors.

if (!fin.is_open()) {
    cerr << "Error: " << strerror(errno);
}

Also, the correct way to read file line-by-line is

std::string line;
while (getline(fin, line)) {
    // Do whatever with line
}

Upvotes: 3

Related Questions