如何确保正确打开文件

How to make sure cin opened the file properly?

本文关键字:文件 何确保 确保      更新时间:2023-10-16

我有这样的代码:

static std :: ifstream s_inF(argv[j]);
std :: cin.rdbuf(s_inF.rdbuf());

我如何确保它正确打开文件并且没有问题?

我的意思是我想写这样的东西:

static std :: ifstream s_inF(argv[j]);
std :: cin.rdbuf(s_inF.rdbuf());
if(.....)
{
  cout << "can not open the file" << endl;
  return 0;
}
...
.....
....
cin.close();

有什么建议吗

所有对象都是std::basic_ios的子类——比如s_inFstd::cin,在你的情况下——如果流准备好进行I/O操作,则operator bool返回true。

这意味着你可以直接测试它们,例如:

static std::ifstream s_inF(argv[j]);
std::cin.rdbuf(s_inF.rdbuf());
if (!s_inF)
{
  cout << "can not open the file" << endl;
  return 0;
}
// ...
cin.close();

您可以使用is_open。在这里看到的:

http://www.cplusplus.com/reference/fstream/ifstream/is_open/