Program crashes after opening file [closed]

2019-02-23 14:34发布

问题:

I need to read values from a file into my program. The file is opening successfully, but then it crashes right away. Is there something wrong with my code?

void createList(intNode*& intList)
{
    intNode* lastInt; //points to last integer in file
    lastInt = NULL;
    int fileInt; //int read from input file
    ifstream intInputFile;

    intInputFile.open("intInput.txt");
    if (intInputFile.is_open())
    {
        cout << "intInput.txt open successful" << endl;
    }
    else
    {
        cout << "intInput.txt open unsuccessful" << endl;
    }
    intInputFile >> fileInt;
    while(!intInputFile.eof())
    {
        intNode* anotherInt;
        anotherInt = new intNode;
        if(intList==NULL)
        {
            intList = anotherInt;
            lastInt = anotherInt;
        }
        else
        {
            lastInt->nextNode = anotherInt;
        }
        lastInt = lastInt->nextNode;
        lastInt->intValue = fileInt;
        lastInt->nextNode = NULL;
        intInputFile >> fileInt;
    }
    intInputFile.close();
    cout << "List created from input file" << endl;
}

Thanks.

Edit:

After checking, I have a problem right after

else
    {
        lastInt->nextNode = anotherInt;
    }

So there must be a problem with this code:

    lastInt = lastInt->nextNode;
    lastInt->intValue = fileInt;
    lastInt->nextNode = NULL;
    intInputFile >> fileInt;

Because I had a cout statement directly after it and it didn't work.

And after looking into it more, the problem is with this line:

     intInputFile >> fileInt;

回答1:

Assuming intList isn't NULL, then you'll call lastInt->nextNode = anotherInt; during your first iteration of the loop while lastInt is still NULL causing the program to crash (due to it following a null pointer).



回答2:

Assuming that the intInput.txt file is formatted properly, your intInputFile >> fileInt; line should read the first integer from it just fine, so there must be some problem with the ifstream. The is_open member function of ifstream only tells you whether the stream has a file associated with it. It doesn't necessarily tell you if there was a problem opening the file. You can check for that with the good function. E.g.:

if (intInputFile.good()) 
    cout << "intInputFile is good" << endl;
else 
    cout << "intInputFile is not good" << endl;

Depending on your system, you may be able to find out the cause of any error using strerror(errno) as follows:

#include <cstring>
#include <cerrno>

...

if (!intInputFile.good())
    cout << strerror(errno) << endl;

This works for me, but see this question for more information as it may not work everywhere.



标签: c++ ifstream