Ifstream crashes program when opening file

不打扰是莪最后的温柔 提交于 2019-12-11 07:56:19

问题


I've narrowed my code down, and I found the source of the problem, it's when I open a file. The file does exists, and I don't get any warning or errors when compiling.

int main(int argc, const char* args[]) 
{
    cout << "Wellcome" << endl;
    cout << args[1];
    ifstream exists(args[1]);
    if(!exists)
    {
        printf("FILE NOT FOUND");
        return 1;
    }
    exists.close();
    ifstream* in;
    in->open(args[1],ios::binary|ios::in);
    //do stuff
    in->close();
    return 0;
}

回答1:


You have created a pointer to an ifstream object, but you never allocated an ifstream for it to point to. To fix this, consider just stack-allocating it:

ifstream in;
in.open(args[1],ios::binary|ios::in);
//do stuff
in.close();

In general, you usually don't need to dynamically allocate objects unless you want them to outlive the function that created them.

Hope this helps!



来源:https://stackoverflow.com/questions/11039618/ifstream-crashes-program-when-opening-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!