I have a C++ document in which I need to open a file. I'm not using a relative path to refer to my file. I'm currently using the full file path on my hard drive, although later I'll switch to just using the current directory. In any case, I know for a FACT that this file is being referred to correctly and is open-able, because I've performed stat() on the filename and it returns all of the correct info about the file. Here's the basic process that's happening:
string fName = "C:\\Users\\[user]\\Downloads\\file.DAT";
ifstream inFile;
inFile.open(fName);
struct _stat buf; // I put these lines here to test that
int result = _stat(fName.c_str(), &buf); // the file is being referred-to right
inFile >> levelnumber;
if(inFile.fail()) // inFile.fail() keeps evaluating to TRUE
ThrowError("Corrupt or inaccesible .DAT file."); // I wrote ThrowError
Anyway, inFile.fail() keeps evaluating to true, even though the file is definitely being referred-to correctly (that's what the call to _stat() checks).
What am I doing wrong? :P
Your test doesn't tell you whether the file could be opened. What your test tells you is that either the file couldn't be opened or levelnumber
couldn't be read. To test if your file was opened, you can check the file right after the call to open()
. If the file is indeed readable, it should convert to true
:
std::ifstream inFile(fName);
if (!inFile) {
std::cerr << "failed to open '" << fName << "' for reading\n";
}