• C++详细的错误测试


    核心概念:所有的流对象都有错误状态位,表示流的状态。

    所有流对象都包含一组充当标志的位。这些标志表示流的当前状态。

    文件状态位标志

    位        描述

    ios::eofbit  在遇到输入流结束时设置。

    ios::failbit  当尝试的操作失败时设置。

    ios::hardfail  当发生不可恢复的错误时设置。

    ios::badbit  当试图进行无效操作时进项设置。

    ios::goodbit  当所有上面的标志没有设置时设置。表示流状态良好。

    上述位可以通过以下列出的成员函数进行测试。其中clear()函数可用于设置状态位:

    报告位标志的成员函数

    函数        描述

    eof()    如果设置了eofbit标志,则返回true(非零);否则返回false。

    fail()    如果设置了failbit或hardfail标志,则返回true(非零);否则返回false。

    bad()        如果设置了badbit标志,则返回true(非零);否则返回false。

    good()   如果设置了goodbit标志,则返回true(非零);否则返回false。

    clear()   当不带参数调用时,清楚上面列出的所有标志。也可以用特定的标志作为参数来调用。

    测试代码:

    #include <iostream>
    #include <fstream>
    using namespace std;

    //Function prototype
    void showState(fstream & );

    int main()
    {
      fstream testFile("stuff.dat", ios::out);
      if(testFile.fail())
      {
        cout<<"Cannot open the file. ";
        return 0;
      }
      int num = 0;
      cout<<"Writting to the file. ";
      testFile<<num;
      showState(testFile);
      testFile.close();

      //Open the same file, read the number, show status
      testFile.open("stuff.dat",ios::in);
      if(testFile.fail())
      {
        cout<<"cannot open the file. ";
        return 0;
      }
      cout<<"Reading from the file. ";
      testFile>>num;
      showState(testFile);

      //Attempt an invalid read, and show status
      cout<<"Forcing a bad read operator. ";
      testFile>>num;
      showState(testFile);

      //close file and quit
      testFile.close();
      return 0;
    }


    void showState(fstream &file)
    {
    cout<<"File Status: ";
    cout<<" eof bit: "<<file.eof()<<endl;
    cout<<" fail bit: "<<file.fail()<<endl;
    cout<<" bad bit: "<<file.bad()<<endl;
    cout<<" good bit: "<<file.good()<<endl;
    file.clear(); //清楚所有不良位
    }

    结果:

    为了进行错误描述,一个流对象的行为就像一个布尔表达式,当没有设置错误标志时为true,否则为false。要检查在流数据文件上执行的上一次操作是否成功,可以使用以下语句:

      if(dataFile)

      {

        cout<<"Success!";

      }

      要检查操作是否因某些错误而失败,可以调用fail()成员函数,也可以使用以下语句:

        if(!dataFile)

        {

          cout<<"Failure!";

        }

  • 相关阅读:
    [转载] kill命令
    [转载] Linux的Top命令解析
    json互相转换
    C# 13位时间戳(unix时间戳)
    第八篇:cx_Oracle出现的问题
    linux:eth网卡对应的物理网口判断
    ls显示前几行或后几行数据
    第七篇:suds.TypeNotFound: Type not found: '(string, http://schemas.xmlsoap.org/soap/encoding/, )'
    第六篇:python中numpy.zeros(np.zeros)的使用方法
    第五篇:selenium调用IE问题(Protected Mode settings are not the same for all zones)
  • 原文地址:https://www.cnblogs.com/ruigelwang/p/12652517.html
Copyright © 2020-2023  润新知