Search code examples
c++stringc++11fstream

fstream included but "ifstream not found" and "identifier is undefined"


I don't know what to make of this. I've written a function that reads a .obj file, not unlike the dozens of other example functions out there for processing information from a text file. I've included fstream, iostream, and sstream. It compiles. Yet when I run it I get:

  • An Unhandled Exception at a memory address (ntdll.dll) that complains about access violation writing location (I'm reading, not writing...).

  • My variable watch on "ifstream myfile" reads identifier "myfile" is undefined". If I place a break on the "ifstream myfile(...)" line it reads "Unable to read memory" instead. Error reading characters of string also occurs just prior to the Unhandled Exception.

  • Execution stops here in fstream during the getline call:

    virtual void __CLR_OR_THIS_CALL _Lock()
    {   // lock file instead of stream buffer
    if (_Myfile)
        _CSTD _lock_file(_Myfile);
    }
    

Relevant code, not much to see... pretty straight forward stuff. "file" is a const char* that reads "C:\cube.obj". Using namespace std.

ifstream myfile(file, ios::in);

if (myfile.is_open())
{
    if (myfile.good())
    {
        string line;
        while (std::getline(myfile, line))
        {
            // Foo
        }
    }
}

myfile.close();

I don't understand how on earth myfile is undefined despite straight up declaring it. fstream is clearly the right include and is accessible. The file is where it should be.

How can I debug this further? Teach me, oh wise ones. Using C++11 with Visual Studio 2013.


Solution

  • SOLVED! I knew it wasn't pointer related. Found this post, tried what it said, and it works flawlessly now. MSVCRTD.lib was missing in my dependencies. Why that's not mentioned anywhere as a prereq for using fstream is crazy. Can't believe the includes aren't enough.

    "I had to change the Runtime Library setting to use Multi-threaded DLL (/MD) and then add: msvcrtd.lib to my dependencies, that solved my problems I was encountering for building in debug mode."

    http://www.gamedev.net/topic/660218-strange-ifstream-crash/