[英]How to make sure cin opened the file properly?
I have this code : 我有这个代码:
static std :: ifstream s_inF(argv[j]);
std :: cin.rdbuf(s_inF.rdbuf());
How can I make sure it opened the file properly and there is no problem ? 如何确保正确打开文件并且没有问题?
I mean I would like to write something like: 我的意思是我想写一些类似的东西:
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();
any suggestion ? 有什么建议吗?
All objects that are subclasses of std::basic_ios
-- like s_inF
and std::cin
, in your case -- have have an operator bool
that returns true if the stream is ready for I/O operations. 作为
std::basic_ios
子类的所有对象(如s_inF
和std::cin
,在您的情况下)都有一个operator bool
,如果流已准备好进行I / O操作,则返回true。
That means you can simply test them directly, eg: 这意味着您可以直接测试它们,例如:
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();
You can use is_open
for this. 你可以使用
is_open
。 See here: 看这里:
http://www.cplusplus.com/reference/fstream/ifstream/is_open/ http://www.cplusplus.com/reference/fstream/ifstream/is_open/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.