打开文件时,ifstream会崩溃程序 [英] Ifstream crashes program when opening file

查看:1078
本文介绍了打开文件时,ifstream会崩溃程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我缩小了我的代码范围,我找到了问题的根源,就是当我打开文件时。
该文件确实存在,编译时我没有收到任何警告或错误。

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


推荐答案

您已创建指向一个 ifstream 对象,但你从未分配过 ifstream 指向它。要解决此问题,请考虑只分配堆栈:

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.

希望这会有所帮助!

这篇关于打开文件时,ifstream会崩溃程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆