user1903336
user1903336

Reputation: 61

ifstream not working

I'm trying to open a file using ifstream, but no matter what solutions I find that I've tried, nothing seems to work; my program always outputs "unable to open". Below is my code in its entirety. Any help at all is appreciated!

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(int argc, char ** argv)
{
    string junk;
    ifstream fin;
    fin.open("somefile.txt");

    if(fin.is_open())
    {
        fin >> junk;
        cout << junk;
    }
    else
    {
        cout << "unable to open" << endl;
    }

    fin.close();
    return 0;
}

Also, the contents of somefile.txt, which is in the same directory as the created executable is the following:

SOME
FILE

Upvotes: 1

Views: 3935

Answers (1)

Nate Hekman
Nate Hekman

Reputation: 6657

As some commenters have suggested, it could easily be that the file truly doesn't exist, because you're looking for it in the wrong place. Try using an absolute path to the file rather than just assuming it's looking where you expect.

And output a more helpful error message using strerror(errno).

// ...
fin.open("C:\\path\\to\\somefile.txt");

// ...
else
{
    cout << "unable to open: " << strerror(errno) << endl;
}

Upvotes: 2

Related Questions