【问题标题】:Why isn't my fstream opening correctly?为什么我的 fstream 没有正确打开?
【发布时间】:2014-04-28 20:03:43
【问题描述】:

我觉得这是一个愚蠢的问题,但我似乎无法弄清楚为什么我的文件没有打开。起初我尝试单独传递文件名,因为它在我的工作目录中,当它不起作用时,我提供了整个路径,这也不起作用。我的文件无法在以下代码中打开是否有原因?这可能是我遗漏的一些非常简单的事情,我认为一双新的眼睛可能会有所帮助。

没有错误代码,因为这是运行时错误。当我调试时,我的代码不会越过if(f.is_open()) 行。我错过了什么吗?我的路径应该是正确的,因为我直接从文件资源管理器复制粘贴它。

欢迎任何帮助,也将不胜感激。

注意:我的 substr 逻辑可能有误,但不要担心那部分代码。

 void QuizKey::readFromFile(string path)
    {

        fstream f;
        f.open(path);

        string line;

        if(f.is_open())
        {
            while(getline(f, line))
            {
                int periodLocation = line.find(".");
                int firstPipe = line.find("|");
                int secondPipe = line.find("|", firstPipe);
                int thirdPipe = line.find("|", secondPipe);

                AnswerSet set;
                set.answer = line.substr(periodLocation + 1, firstPipe - periodLocation - 1);
                set.two = line.substr(firstPipe + 1, secondPipe - firstPipe - 1);
                set.three = line.substr(secondPipe + 1, thirdPipe - secondPipe - 1);
                set.four = line.substr(thirdPipe + 1, line.length() - thirdPipe - 1);

                key.push_back(set);
            }
        }
    }

【问题讨论】:

    标签: c++ fstream getline


    【解决方案1】:

    如果您在 Windows 中并直接从资源管理器复制和粘贴,那么您可能忘记转义文件路径中的斜杠,它应该是 "c:\\foo\\bar.txt"

    另外,open() 不接受char*,而f.open(path.c_str()) 需要是f.open(path.c_str())

    【讨论】:

    • C++11 为basic_fstream<CharT>::open 添加了std::string 重载。
    • 哦,那太好了 - 我还没有达到 C++11
    • 我现在看到了问题:从资源管理器复制粘贴时,我在前面得到一个额外的花絮:file:///C:/Users/Zachary/Documents/GitHub/Quiz_Maker/TestKey.txt我忘了删除。这解决了问题,但您的回答为我指明了正确的方向。谢谢你。 @MrZebra
    • IIRC 正斜杠也可以工作:"c:/foo/bar.txt"
    • 是的,正斜杠很好,不需要转义或其他英勇的措施。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多