我正在尝试使用C++进行try,catch,throw语句处理文件,并且我编写了一个虚拟代码来捕获所有错误.我的问题是为了检查我是否有这些权利,我需要发生错误.现在,我可以infile.fail()通过简单地不在目录中创建所需名称的文件来轻松检查.但是,我怎么就能检查同为outfile.fail()(outfile是ofstream这里的infile是ifstream).在哪种情况下,值outfile.fail()是真的吗?
示例代码[来自对unapersson的回答的评论,简化为使问题更清晰 - -zack]:
#include <fstream>
using std::ofstream;
int main()
{
ofstream outfile;
outfile.open("test.txt");
if (outfile.fail())
// do something......
else
// do something else.....
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*obᵩ 27
open(2)Linux上的手册页有大约30个条件.一些有趣的是:
char*的文件名.小智 6
默认情况下,按照设计,C++流永远不会在出错时抛出异常.您不应该尝试编写假设它们的代码,即使它可以使用它们.相反,在您的应用程序逻辑中检查每个I/O操作是否有错误并处理它,如果该错误无法在代码中出现的特定位置处理,则可能会抛出您自己的异常.
除非必须,否则测试流和流操作的规范方法不是测试特定的流标志.代替:
ifstream ifs( "foo.txt" );
if ( ifs ) {
// ifs is good
}
else {
// ifs is bad - deal with it
}
Run Code Online (Sandbox Code Playgroud)
类似的读操作:
int x;
while( cin >> x ) {
// do something with x
}
// at this point test the stream (if you must)
if ( cin.eof() ) {
// cool - what we expected
}
else {
// bad
}
Run Code Online (Sandbox Code Playgroud)
要ofstream::open失败,您需要安排它不可能创建命名文件。最简单的方法是在运行程序之前创建一个完全相同名称的目录。这是一个几乎完整的演示程序;当且仅当您创建测试目录时,安排可靠地删除它,我将其留作练习。
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#include <cstring>
#include <cerrno>
using std::ofstream;
using std::strerror;
using std::cerr;
int main()
{
ofstream outfile;
// set up conditions so outfile.open will fail:
if (mkdir("test.txt", 0700)) {
cerr << "mkdir failed: " << strerror(errno) << '\n';
return 2;
}
outfile.open("test.txt");
if (outfile.fail()) {
cerr << "open failure as expected: " << strerror(errno) << '\n';
return 0;
} else {
cerr << "open success, not as expected\n";
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
没有好的方法可以确保写入fstream 失败。如果我需要测试,我可能会创建一个写入失败的模拟 ostream。
| 归档时间: |
|
| 查看次数: |
46511 次 |
| 最近记录: |