【问题标题】:ifstream::is_open returns true even if file is not existing at the location即使文件在该位置不存在,ifstream::is_open 也会返回 true
【发布时间】:2019-04-03 01:03:17
【问题描述】:

我有一个函数,它基本上从该位置打开文件,并将文件中可用的值解析为源代码的其他一些地方使用的某种结构。 这里的问题是即使文件在上述位置不可用,ifstream::isopen 也会返回 true

我尝试使用 ifstream::open 显式打开文件而不是使用构造函数,但不幸的是它不起作用。

bool ClassName::loadRecordingConfiguration() 
{
     std::string filepathConfig = getDataFolder() + std::string("\\file.json");
     std::ifstream jsonFile(filepathConfig.c_str());
     if (jsonFile.is_open()) {
         //This part is executed when getDataFolder failed to return the folder path and file.json is not available
         //This part is also executed when getDataFolder returns correct folder path and file.json is available
     }
}

//Returns the folder path if SomeCondition is satisfied
std::string ClassName::getDataFolder() 
{
    if (SomeCondition) {
        return std::string(SomeFilePath);
    }
    return std::string("");
}

由于文件夹路径不正确,我希望它只有在我将 file.json 放置在 soomeFilePath 位置时才能工作

【问题讨论】:

  • getDataFolder() 失败时,它是否会像显示的那样返回一个空刺?如果是这样,您是否检查过./file.json 不存在,其中. 表示您执行程序的工作目录?或者file.json 完全不存在——但is_open() 仍然返回true?此外,填写占位符名称并或多或少地显示当前目录树以获得最小的工作示例会有所帮助。
  • 你说:“我没有使用构造函数,而是使用 ifstream::open 显式打开文件。”。但是在您的示例中,您实际上使用构造函数来打开它。 std::ifstream jsonFile(filepathConfig.c_str());
  • @anakhand 是的,当 getDataFolder 失败时,它会返回显示的空字符串。我确保 file.json 在工作目录中的任何地方都不存在..
  • @Oliort 我再次更新了 cmets。抱歉描述不正确
  • 知道如果路径中没有提到的文件,ifstream 如何打开文件吗??

标签: c++


【解决方案1】:

尝试使用operator bool (if (jsonFile){ ... }) 或检查流标志(badbit、failbit)。打开文件是非常特定于操作系统的操作,ifstream::is_open() 仅检查它是否设法创建文件句柄。

在任何情况下,最好先使用某些 OS API 检查它是否存在(例如,PathFileExistsA 用于 Windows)。

【讨论】:

  • ifstream::good() 一次检查所有错误位。
  • @oliort 我发现了问题。当 getDataFolder() 返回 NULL filepathConfig=\file.json。在 GetFullPathName API 的帮助下,我找到了绝对路径,并且文件是从当前目录中获取的,在我的例子中是 U:\file.json。我删除了该文件,它对我有用。感谢您指引我走上正确的道路。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-19
  • 2012-01-14
  • 1970-01-01
  • 2015-11-16
  • 2016-11-03
  • 2019-10-13
  • 1970-01-01
相关资源
最近更新 更多