gpt4 book ai didi

c++ - ifstream.open() 不打开文件

转载 作者:行者123 更新时间:2023-12-01 14:41:15 35 4
gpt4 key购买 nike

今晚我一直在做噩梦,试图让一些非常简单的 I/O 功能运行。虽然很尴尬,但我从这里的人那里得到了很大的帮助!

我当前的问题是,我正在尝试使用 ifstream.open(),但它根本无法打开文件。这由 getline(ifstream,line) 确认;在第一次调用时返回 false。

这是当前代码的复制粘贴:

std::string FSXController::readLine(int offset, FileLookupFlag flag)
{
// Storage Buffer
string line;
streampos sPos(offset);

try
{
// Init stream
if (!m_ifs.is_open())
m_ifs.open("C:\\Users\\guyth\\Documents\\test.txt", fstream::in);
}
catch (int errorCode)
{
showException(errorCode);
return "";
}

// Set stream to read input line
m_ifs.seekg(sPos);
if (!getline(m_ifs, line))
return "";

// Close stream if no multiple selection required
if (flag == FileLookupFlag::single)
m_ifs.close();

return line;

}

此代码处于“错误修复模式”,因此非常困惑,不要太担心,当此方法最终起作用时会进行清理。

我试过:

  • 绝对文件路径
  • 将路径保存到字符串中,然后调用 .c_str() 方法。
  • 在管理员模式下运行 VS 2015
  • 确保文件具有读/写权限
  • 确保没有重复的文件扩展名
  • 是的,文件肯定有内容! :D

我现在有点不知所措,我真的不确定为什么这个文件拒绝加载。

条件:if (!getline(m_ifs, line)) 重复返回 true... :(

编辑:我刚刚尝试在打开后立即检查 m_ifs.fail() 并返回 true,因此我们知道失败标志已被触发:/

谢谢

家伙

最佳答案

在打开流之前启用异常:

m_ifs.exceptions ( std::ifstream::failbit | std::ifstream::badbit );

否则 m_ifs.open 不会抛出。

而且你必须捕获std::ifstream::failure:

  try {
m_ifs.open("C:\\Users\\guyth\\Documents\\test.txt", fstream::in);
}
catch (std::ifstream::failure e) {
std::cerr << "Exception opening file: " << std::strerror(errno) << "\n";
}

参见 ios::exceptions了解更多详情。

关于c++ - ifstream.open() 不打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39213989/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com