【问题标题】:Trouble opening file in C++无法在 C++ 中打开文件
【发布时间】:2012-01-11 05:34:56
【问题描述】:

我无法打开文件进行阅读,我无法完全弄清楚我做错了什么,也许我给出路径的方式有问题,但我不知道。

/*
output:
Where is the conversion table ?
/Users/awiebe/Documents/Langara\ Assignments/CPSC1160/CURRENCYCODES.txt 
Unable to open file
*/


StringFloatMap readFile(string path)
{
    //fstream filestr ("test.txt", fstream::in | fstream::out);
    ifstream filestr;
    const char* cPath = path.c_str();
    filestr.open(cPath);

    if (filestr.is_open())
    {
        filestr.close();
    }
    else
    {
        cout << "Unable to open file" << endl;
    }
/*…*/
}

【问题讨论】:

  • cout
  • 尝试使用完整路径调用此函数(如/Users/awiebe/Documents/test.txt)。还要确保该文件存在并且您对其具有写入权限。
  • 真的有写权限吗?
  • 是的,因为它以写入选项打开。

标签: c++ io ifstream


【解决方案1】:

您不需要转义路径中的空格字符(例如,您可以删除文件名中的 \)。

【讨论】:

  • 什么转义字符 - 它只是一个评论
  • @AdrianCornish:顶部的注释似乎是运行程序后的输出(包括提示“转换表在哪里?”我们没有看到代码)。在这种情况下,alanxz 是正确的,在交互式提示下输入时,空格之前不应有 \。最简单的解决方案是避免在目录名称中使用空格。
【解决方案2】:

cPath 变量不是必需的(但可能有助于调试)

我建议打印失败消息。添加

#include <cstring>
#include <cerrno>

cout << "Unable to open file:" << errno << ':' << strerror(errno) << std::endl;

【讨论】:

    【解决方案3】:

    只要去掉“\”并给他路径: 例如:

    /Users/awiebe/Documents/Langara Assignments/CPSC1160/CURRENCYCODES.txt

    由于您使用字符串类,因此不需要对空格使用转义序列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多