在 qt 中使用 ifstream 打开文件时出现问题

Issue opening file with ifstream in qt

本文关键字:文件 问题 qt ifstream      更新时间:2023-10-16

我的搭档在文本编辑器中为我的一个项目写了一堆代码,当我运行代码时,它运行得很好......现在我已经将所有代码复制并粘贴到Qt Creator中,我遇到了一个问题

 stringstream ss;
            string line;
            ifstream myfile;
            myfile.open("Instructors.txt");
            if (myfile.is_open()){
                while (getline(myfile,line)){
                    ss << line << ", ";
                }
                myfile.close();
            }
            else cout << "bad open" << endl;

以上是我的代码出现问题的部分,我可以向所有讲师保证.txt确实在正确的文件中,但是每次我们的代码达到打开文件的这一点时,我都会被扔到其他"糟糕的打开"为什么会这样?

如果没有任何错误代码,很难说它可能是什么,您可以做的是用更有意义的东西(对您和您的客户)来改进您的错误消息:

else cout << "Error opening file: " << strerror(errno) << endl;

strerror(请参阅参考)函数返回宏捕获的给定错误代码errno字符串。

否则,您可以使用异常来C++:首先为您的流启用它们:

myfile.exceptions(ifstream::failbit | ifstream::badbit);

然后抓住它们,一起就是:

try
{
    ifstream myfile("Instructors.txt");
    myfile.exceptions(ifstream::failbit | ifstream::badbit);
    while (getline(myfile, line))
    {
        ss << line << ", ";
    }
    myfile.close();
}
catch (ifstream::failure e)
{
    cout << e.what() << endl;
}

尝试重写文件名,可能是它包含来自不同编码的字符。

仔细检查工作目录,很可能它在构建文件夹中(可执行文件被删除的地方)

在QtCreator中,您可以通过转到项目并选择运行来解决此问题;在那里您将能够设置工作目录