Error in std::getline function (fstreeam _Lock())

1

I keep getting an error when call std::getline, the debugger shows a break in a fstream function """virtual void __CLR_OR_THIS_CALL _Lock()"""

Here is my code (Read File function):

string GetFile(const string& fileName)
{
    string line;
    string output;
    ifstream myfile (fileName);
    myfile.open(fileName);//.c_str());

    if (myfile.is_open())
    {
        while ( getline (myfile,line) )
        {
            //cout << line << '\n';
            output.append(line + "\n");
        }
        myfile.close();

    } else cout << "Unable to open file";

    return output;
}

(ADDED)
the break message:

Unhandled exception at 0x7787FC47 (ntdll.dll) in Engine.exe: 0xC0000005: Access violation writing location 0x00000014.

and the break in fstream shows this function:

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

I Have no idea what is the problem

c++
file
locking
getline
asked on Stack Overflow Aug 24, 2014 by lightbug • edited Aug 24, 2014 by lightbug

3 Answers

0

It's not an answer but it's a start. I've made a new project and use this code (the same that always):

#define Dir "C:\\difuseVS.txt"

using namespace std;

string GetFile(const string& fileName)
{

string line;
string output;
ifstream myfile(fileName);


if (myfile)
 {

     while ( getline (myfile,line) )
    {
      //cout << line << '\n';
      output.append(line + "\n");
    }
 myfile.close();

}else cout << "Unable to open file"; 

return output;
}

int main()
{
cout << GetFile(Dir);
getchar();

}

And it works perfectly!! the problem is in the project configuration, but I don't know where exactly

answered on Stack Overflow Aug 25, 2014 by lightbug
0

Trapped by same problem, I found this link give me some clue. http://www.heapoverflow.me/question-fstream-included-but-ifstream-not-found-and-identifier-is-undefined-26761708

For my env(vs2010), I just added msvcrtd.lib to my Project Property->Linker->Input->additional dependencies and the headache gone, as my Runtime Library is Multi-threaded DLL (/MD) already, if not then probably need to set it as well

answered on Stack Overflow Oct 5, 2015 by liyi3c
0

The constructor:

ifstream myfile (fileName);

opens the file. Then:

myfile.open(fileName);

should fail; see ifstream::open - C++ Reference that says "If the stream is already associated with a file (i.e., it is already open), calling this function fails". Of course, it seems that "myfile.is_open()" should return FALSE. Since this is an old question I assume it is not worth pursuing further but perhaps this will help someone in the future in the unlikely event that the same problem is encountered.

answered on Stack Overflow Apr 14, 2017 by user34660

User contributions licensed under CC BY-SA 3.0