【问题标题】:Program crashes after opening file [closed]打开文件后程序崩溃[关闭]
【发布时间】:2012-12-19 00:56:44
【问题描述】:

我需要将文件中的值读入我的程序。该文件已成功打开,但随后立即崩溃。我的代码有问题吗?

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;
}

谢谢。

编辑:

检查后发现问题

else
    {
        lastInt->nextNode = anotherInt;
    }

所以这段代码肯定有问题:

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

因为我在它之后直接有一个 cout 语句,但它不起作用。

在仔细研究之后,问题出在这一行:

     intInputFile >> fileInt;

【问题讨论】:

  • 你能添加更多 cout 来找到代码崩溃的确切位置吗?
  • 如果它崩溃了,那么是的,你的程序有问题。
  • 好的,我现在就试试。
  • 你现在要尝试什么?
  • @ScottHunter Josay 推荐了什么。

标签: c++ ifstream


【解决方案1】:

假设intList 不是NULL,那么您将在循环的第一次迭代期间调用lastInt-&gt;nextNode = anotherInt;,而lastInt 仍然是NULL 导致程序崩溃(由于它跟随一个空指针)。

【讨论】:

  • 我的程序由于以下语句而崩溃:intInputFile >>fileInt;
  • 这与您编辑后的帖子“我马上有问题”不符。你应该编辑你的问题。还可以尝试在该行设置一个断点,并在到达它时验证您的流是否正常。
  • 好的,我做到了。我事先知道一切都很好,我认为问题出在我的原始值文件中。我制作了一个包含 5 个整数的文件,当我的程序尝试读取下一个整数时,它崩溃了。我将文件中的每个整数值放在单独的行上,可以吗?
  • 不确定我的理解是否正确,但这应该可以正常工作:如果输入无效,则该值将设置为 0 并且程序仍将继续运行 - 它不会崩溃.流很可能有问题。
  • 哦,好吧,我是新手,所以你说的流有问题是什么意思?
【解决方案2】:

假设intInput.txt 文件格式正确,您的intInputFile &gt;&gt; fileInt; 行应该可以很好地读取其中的第一个整数,所以ifstream 一定有问题。 ifstreamis_open 成员函数只告诉您流是否有与之关联的文件。它不一定会告诉您打开文件是否有问题。您可以使用 good 函数来检查。例如:

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

根据您的系统,您可以使用strerror(errno) 找出任何错误的原因,如下所示:

#include <cstring>
#include <cerrno>

...

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

这对我有用,但请参阅this question 了解更多信息,因为它可能并非在任何地方都有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    相关资源
    最近更新 更多